다양한 숫자 체계 간 변환

CBeginner
지금 연습하기

소개

숫자 체계는 서로 다른 기호와 수학적 연산을 사용하여 숫자를 표현하는 방법입니다. 서로 다른 숫자 체계 간의 변환은 프로그래밍에서 흔히 사용되는 작업입니다. 이 랩에서는 한 시스템에서 다른 시스템으로 숫자를 변환할 수 있는 프로그램을 소개합니다. 다음 내용을 다룹니다.

  • 이진수에서 십진수로의 변환 (Binary to Decimal Conversion)
  • 팔진수에서 십진수로의 변환 (Octal to Decimal Conversion)
  • 십진수에서 이진수로의 변환 (재귀 없이) (Decimal to Binary Conversion (without recursion))
  • 십진수에서 이진수로의 변환 (재귀 포함) (Decimal to Binary Conversion (with recursion))

참고: 코딩을 연습하고 gcc 를 사용하여 컴파일하고 실행하는 방법을 배우려면 직접 ~/project/main.c 파일을 생성해야 합니다.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

이진수에서 십진수로 변환

이진수는 0 과 1 의 두 자리 숫자만 사용하는 숫자 체계입니다. 십진수는 0 부터 9 까지의 10 자리 숫자를 사용하는 숫자 체계입니다. 다음은 이진수를 십진수 값으로 변환하는 C 프로그램입니다.

#include<stdio.h>
#include<math.h>

// 함수 프로토타입 선언 (Function prototype declaration)
int binary_decimal(int n);

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    int n;
    char c;
    printf("Enter the binary number: ");
    scanf("%d", &n);
    printf("\n\n\nThe decimal equivalent of %d is  %d\n\n", n, binary_decimal(n)); // 함수 호출 (function calling)
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

// 이진수를 십진수로 변환하는 함수 정의 (Definition of the function to convert binary to decimal.)
int binary_decimal(int n)
{
    int decimal = 0, i = 0, rem;
    while(n != 0)
    {
        rem = n%10;   // 일의 자리 숫자를 반환 (gives the digit at the units place)
        n = n/10; // 일의 자리 숫자를 제외한 숫자를 반환 (gives the number excluding its units digit)
        /*
            pow 는 두 개의 정수를 입력 매개변수로 사용하는
            시스템 정의 함수입니다. (pow is a system defined function that takes
            two integers as input parameters)
        */
        decimal += rem*pow(2, i++);
    }
    /*
        입력된 이진수의 십진수 값을
        함수 호출로 반환합니다. (return the decimal equivalent of the input
        binary number to the function call)
    */
    return decimal;
}

팔진수에서 십진수로 변환

팔진수는 0 부터 7 까지의 8 자리 숫자를 사용하는 숫자 체계입니다. 다음은 팔진수를 십진수 값으로 변환하는 C 프로그램입니다.

#include<stdio.h>
#include<math.h>

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    long int octal, val, decimal = 0;
    int i = 0;
    printf("Enter any octal number: ");
    scanf("%ld", &val);
    octal = val;
    while(octal != 0)
    {
        /*
            i++ 는 후위 증가 연산자로, 값이
            먼저 할당된 후 증가합니다. (i++ is post increment, where value is
            first assigned and then incremented)
        */
      decimal += (octal % 10)*pow(8, i++);
      octal/=10;    // octal=octal/10 과 동일 (same as octal=octal/10)
    }
    printf("\n\n\nEquivalent decimal value of %ld is %ld\n\n\n", val, decimal);
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

십진수에서 이진수로 변환 (재귀 없이)

다음은 재귀 없이 십진수를 이진수 값으로 변환하는 C 프로그램입니다.

#include<stdio.h>

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    int n,c,k;
    printf("Enter an integer in decimal number system: ");
    scanf("%d", &n);

    // 31 비트 형식 (In 31 bit format)
    printf("\n\n\nThe binary equivalent of decimal value %d is:", n);

    for(c = 31; c >= 0; c--)
    {
        k = n>>c;
        /*
            num&1 = num 의 마지막 자릿수가 1 이면 true 를 반환합니다.
            그렇지 않으면 false 를 반환합니다. (num&1 = returns true if the last digit of num is 1
            else false)
        */
        if(k&1)
            printf("1");
        else
            printf("0");
    }
    printf("\n");
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

십진수에서 이진수로 변환 (재귀 사용)

다음은 재귀를 사용하여 십진수를 이진수 값으로 변환하는 C 프로그램입니다.

#include<stdio.h>

// 함수 원형 선언 (Function prototype declarations)
void decimal_binary(int );
void F(int );
void reverse(int );

int main()
{
    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");
    int n;
    printf("\n\nEnter an integer in decimal number system: ");
    scanf("%d", &n);

    // 31 비트 형식 (In 31 bit format)
    printf("\n\nThe binary equivalent of decimal value %d using decimal_binary method is: ", n);

    decimal_binary(n);  // 함수 호출 (function call)

    printf("\n\nThe binary equivalent of decimal value %d using F() method is: ", n);
    F(n);   // 함수 호출 (function call)
    printf("\n\nThe Reverse of the binary representation of value %d is: ", n);
    reverse(n); // 함수 호출 (function call)
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

// 함수 정의 (function definition)
void decimal_binary(int i)
{
    if(i <= 1)
    printf("%d", i);   // 위에서 아래로 형식으로 출력 (to print in up to down format)
    else
    {
        decimal_binary(i/2);
        printf("%d", i%2);
    }
}

void F(int j)
{
    if(j/2)
    {
        F(j/2);
    }
    printf("%d", j%2);
}

void reverse(int k)
{
    if(k <= 1)
        printf("%d", k);
    else
    {
        printf("%d", k%2);
        F(k/2);
    }
    printf("\n\n");
}

요약

이 랩에서는 다양한 숫자 체계 간에 숫자를 변환할 수 있는 프로그램을 선보였습니다. 이진수에서 십진수로의 변환, 팔진수에서 십진수로의 변환, 그리고 십진수에서 이진수로의 변환 (재귀 사용 및 미사용) 을 다루었습니다. 이 랩을 통해 C 프로그래밍에서 다양한 숫자 체계 간에 숫자를 변환하는 방법을 이해하는 데 도움이 되었기를 바랍니다.