컴퓨터 엑셀 워드 포토샵 구글어스 WINDOWS JAVASCRIPT JAVA C++

 
Friday, October 13, 2006

C언어] 10진수 2진수 진법 변환, 이진수 출력 함수: Decimal to Binary (base-2)


C언어 자체에는 십진수를 이진수로 변환하는 함수가 없기에, 비트 연산으로 직접 만들어야 합니다. 다음은 10/16진수 숫자를 2진수 문자열로, 2진수 문자열을 10/16진수 정수로 만드는 함수입니다. 32비트 정수용입니다.

프로그래밍에서 2진수를 직접 다루어야 하는 경우는 드물고, 대부분 10진수나 16진수를 사용합니다. 따라서 "00100110000110000100111000001110" 이런 2진수는 숫자가 아닌 그냥 평범한 문자열로서만 인식됩니다.

Binary 가 2진수이고, Decimal 이 10진수입니다.

10진수/16진수 <-> 2진수 변환 출력 예제


파일명: 0.cpp
#include <stdio.h>


char *intToBinary(int i);           // 부호 있는 32비트 정수를, 2진수 문자열로 변환
char *uintToBinary(unsigned int i); // 부호 없는 32비트 정수를, 2진수 문자열로 변환

int binaryToInt(char *s);           // 2진수 문자열을, 부호 있는 32비트 정수로 변환
unsigned int binaryToUint(char *s); // 2진수 문자열을, 부호 없는 32비트 정수로 변환


void main(void) {
  puts("\n\nDecimal to Binary (int) :\n");

  printf("%s\n",  intToBinary(0x0));
  printf("%s\n",  intToBinary(0xFF));
  printf("%s\n",  intToBinary(0xFFFF));
  printf("%s\n",  intToBinary(-2147483647 - 1)); // int 최소값 = -2147483648
  printf("%s\n",  intToBinary(2147483647));      // int 최대값
  printf("%s\n",  intToBinary(639127054));       // 임의의 값


  puts("\n\nDecimal to Binary (unsigned int) :\n");

  printf("%s\n", uintToBinary(0x0));
  printf("%s\n", uintToBinary(0xF));
  printf("%s\n", uintToBinary(0xFF));
  printf("%s\n", uintToBinary(0xFFFF));
  printf("%s\n", uintToBinary(0xFFFFFFFF)); // unsigned int 최대값


  puts("\n\nBinary to Decimal (int):");

  printf("%d\n", binaryToInt("0"));
  printf("%d\n", binaryToInt("1111"));
  printf("%d\n", binaryToInt("11111111"));
  printf("%d\n", binaryToInt("1111111111111111"));
  printf("%d\n", binaryToInt("00000000000000001111111111111111"));
  printf("%d\n", binaryToInt("01111111111111111111111111111111"));


  puts("\n\nBinary to Decimal (unsigned int):");

  printf("%u\n", binaryToUint("0"));
  printf("%u\n", binaryToUint("1111"));
  printf("%u\n", binaryToUint("11111111"));
  printf("%u\n", binaryToUint("1111111111111111"));
  printf("%u\n", binaryToUint("00000000000000001111111111111111"));
  printf("%u\n", binaryToUint("11111111111111111111111111111111"));
  printf("%u\n", binaryToUint("00100110000110000100111000001110"));

}




char *intToBinary(int i) {
  static char s[32 + 1] = { '0', };
  int count = 32;

  do { s[--count] = '0' + (char) (i & 1);
       i = i >> 1;
  } while (count);

  return s;
}


char *uintToBinary(unsigned int i) {
  static char s[32 + 1] = { '0', };
  int count = 32;

  do { s[--count] = '0' + (char) (i & 1);
       i = i >> 1;
  } while (count);

  return s;
}



int binaryToInt(char *s) {
  int i = 0;
  int count = 0;

  while (s[count])
    i = (i << 1) | (s[count++] - '0');

  return i;
}


unsigned int binaryToUint(char *s) {
  unsigned int i = 0;
  int count = 0;

  while (s[count])
    i = (i << 1) | (s[count++] - '0');

  return i;
}



실행 결과:
D:\Z>cl 0.cpp && 0.exe
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

0.cpp
Microsoft (R) Incremental Linker Version 7.10.3077
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:0.exe
0.obj


Decimal to Binary (int) :

00000000000000000000000000000000
00000000000000000000000011111111
00000000000000001111111111111111
10000000000000000000000000000000
01111111111111111111111111111111
00100110000110000100111000001110


Decimal to Binary (unsigned int) :

00000000000000000000000000000000
00000000000000000000000000001111
00000000000000000000000011111111
00000000000000001111111111111111
11111111111111111111111111111111


Binary to Decimal (int):
0
15
255
65535
65535
2147483647


Binary to Decimal (unsigned int):
0
15
255
65535
65535
4294967295
639127054

D:\Z>



printf("%s\n", intToBinary(-2147483648));

int 최소값인 -2147483648 을 직접 지정하면, warning C4146: unary minus operator applied to unsigned type, result still unsigned (부호 없는 정수형에, 마이너스 부호를 지정했다) 라는 경고가 나오기에,

printf("%s\n", intToBinary(-2147483647 - 1));
이런 식으로 표현했습니다.




intToBinary() 함수에서

static char s[32 + 1] = { '0', };

이것을 static 으로 하지 않으면, warning C4172: returning address of local variable or temporary 이런 워닝이 납니다. 지역 변수의 주소를 반환하려고 했다는 경고입니다. 지역 변수는 그 함수가 종료되면 자동으로 사라지기에 기껏 주소를 반환해도 "주막 없는 번지"가 되어 버립니다. static 변수로 만들면, 함수가 종료되어도 변수가 사라지지 않게 됩니다.



▶▶ C언어] 십진수 정수, 16진수 헥사(Hex)로 변환/출력 함수? 방법은?


strtoul() 함수로 변환: ▶▶ C언어] 2진수 문자열을, 10진수 정수 숫자로 변환 함수; Base-2 String to Int Number


16진법 2진법 10진수 상호 변환기 (온라인 버전): ▶▶ 16진수 헥사, 2진수, 10진수, 8진법 변환 계산기; Hex Calc

2 Comments:
At March 24, 2017 at 10:35 PM, Blogger Unknown said...

저기 혹시 죄송한데 아래 코딩 부분 설명좀 해주실수 있으세요??

char *intToBinary(int i) {
static char s[32 + 1] = { '0', };
int count = 32;

do {
s[--count] = '0' + (char)(i & 1);
i = i >> 1;
} while (count);

return s;
}

 
At March 25, 2017 at 7:04 PM, Blogger mwultong said...

static char s[32 + 1] = { '0', };
# 32글자 이진수 문자열을 넣을 배열 s 를 정의하고 '0'이라는 문자로 초기화합니다.
# + 1 은 문자열의 끝을 알리는 null 문자를 넣을 공간 확보.

int count = 32;
# 루프를 돌리는 데 쓸 카운터 숫자
# 32글자 이진수 문자열이므로 당연히 32

# 배열 s 의 인덱스에 --count 를 넣으면 31부터 0까지 거꾸로 루프를 돌리게 됩니다.
# (char) 는 정수 숫자를 문자로 캐스팅(변환)

& 연산자: 비트 단위의 AND 연산자
>> 는 "오른쪽 시프트 연산자"

비트 연산이 핵심인데, 구글에서 C 비트 연산자로 찾아 보세요.

비트 연산 부분은 제가 만든 것이 아니고 외국 게시판에 있던 것입니다^^;

 

Post a Comment

<< Home RSS 2.0 feed

구글 Google 에서 제공하는 무료 블로그 서비스인 블로거 Blogger 의 인터넷 주소는 www.blogger.com 입니다. Blogger 에 블로그를 만들면, blogspot.com 이라는 주소에 블로그가 생성됩니다.
블로그를 직접 방문하지 않고도 최신 게시물을 구독하려면 RSS 2.0 feed 주소를 리더기에 등록하시면 됩니다.
Previous Posts
Monthly Archives
Top