정수를 이진수 문자열로 바꾸려하는데

geneven의 이미지

C언어에서 정수를 이진수 문자열로 바꾸려고 합니다. 어떤 방법이 있죠?

File attachments: 
첨부파일 크기
Binary Data Chapter15.hwp111.28 KB
deisys의 이미지

정수가 4바이트라고 가정하면,

For i = 31 to 0 
    if ( ( integer >> i ) & 0x0001 )
        str.append(1)
    else
        str.append(0)

같은 방식으로 하면 되지 않을까요?...? (C코드는 아닙니다만)
이런걸 원하시는게 아니라면 대략 낭패 ... ;;

서지훈의 이미지

관련 라이브러리는 없는것 같고...
직접 계산을 하셔서 실행가능하게 만드셔야 할듯 하네요...-_-ㅋ

만약 minus(-) 값은 없는걸로 한다면...
그냥 bit만 찍는걸로 해도 될거 같군요...
여기에 대한 예제는 ABC 이 책에 나와있으니 참고 하시길...

<어떠한 역경에도 굴하지 않는 '하양 지훈'>

#include <com.h> <C2H5OH.h> <woman.h>
do { if (com) hacking(); if (money) drinking(); if (women) loving(); } while (1);

bear의 이미지

int i, temp, temp2;
char bin[50];

for(i=0;i<50;i++) bin[i]="2";

scanf("%d",&temp);

i=49;

while(temp <= 1){
      temp=temp/2;
      temp2=temp%2;
      temp2=bin[i];
      i--;
}

for(i=0;i<50;i++){
	if(bin[i] !=2) printf("%c",bin[i]);
}

대충이나마 만들어 봤네요..^^;;;

허접해서..^^;;;

도움이 되길..^^;;

전혀 알고리즘에 신경 안씀, 생각나는데로 만들어 봤네요..^^;;;;

세벌의 이미지

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
	const int len=sizeof(int)*8;
	int bin[len];
	int num;
	int i;

	if(argc!=2){printf("usage %s number", argv[0]); return 0;}

	for(i=0;i<len;i++)
		bin[i]=0;

	num=atoi(argv[1]);
	printf("%d\n", num);
	for(i=len-1; i>=0; i--){
		bin[i] = (num>>i) & 1;
	}
	for(i=len-1; i>=0; i--){
		printf("%d", bin[i]);
	}

	return 0;

}

문자 배열로 바꾸는 건 더 손 대기 귀찮아서 -.- 다른 분이 잘 답변 해주시겠죠 :)

nanosec의 이미지

문서 첨부 합니다.
저도 어디서 구했는지 가물 가물 한데

바로 쓸수 있는 알고리즘이 몆가지 소스와 함께 소개되어 있습니다.

댓글 첨부 파일: 
첨부파일 크기
Binary Data 0바이트

0x2B | ~0x2B
- Hamlet

aniseeker의 이미지

질문과는 관련없는 내용이지만..

이 친절함은 정말이지 대한민국 만세로군요. (^-^)b

모두 복받으실 겁니다.

어두운 밤에 움직이지 않는 꽃과 개와 물,
어두운 밤에 꽃과 짖는개와 물.

fibonacci의 이미지

주어진 자연수 a 가 1보다 크다는 가정 하에서 2진수로 "거꾸로" 변환하여 출력합니다.
배열 약간 쓰면 원래 모양대로 나오게 하는건 쉽겠죠.
가장 무난하고도 교과서적인 방법입니다.

while(a!=1)
{
    printf("%d", a%2);
    a = (a - a%2)/2;
}
printf("1");

No Pain, No Gain.

vacancy의 이미지

performance가 그다지 중요하지 않다면 ..

void print_bin(int n) {
  if (n == 0) return;
  print_bin(n / 2);
  printf("%d", n % 2);
}

.. 같은 함수를 써도 되잖을까 싶네요 ..
( 바로 친거라 어디 틀린데가 있을지도 -_-; )

envia의 이미지

대강 짜 보면,

char* convert(int a)
{
        int i;
        char* s = (char*)malloc(33);

        for(i=0;i<32;i++)
                s[31-i] = '0' + ((a >> i) & 1);
        s[32]=0;

        return s;
}

쓰고보니 deisys님의 코드와 비슷하군요.

----

It is essential, if man is not to be compelled to have recourse, as a last resort, to rebellion against tyranny and oppression, that human rights should be protected by the rule of law.
[Universal Declaration of Human Rights]

세벌의 이미지

답변들을 죽 보니, 나누기를 이용한 방법, 쉬프트연산자를 사용한 방법 크게 두가지가 있네요. 재귀호출을 사용하신 분까지 있고.

나누기를 이용한 방법은 이해하기 쉽고, 속도느림.
쉬프트연산자사용한 방법은 이해하기 어렵고, 속도 빠름. 그러나 쉬프트연산자도 익숙해지면 그리 어렵지 않습니다.

cskblue의 이미지

    for( i=32; i>0; i-- )
        printf("%d", (dec >> (i-1)) & 0x01);

전체 코드로 보면

int main()
{
    int dec,i;
    printf("Input interger : ");
    scanf("%d",&dec);
    printf("\n%d --> ",dec);
    i = (sizeof(int)*8 );              // 이식성 ;;

    for(i; i > 0 ; i--)
    {
        if(i%8 == 0) printf(" ");       // 가독성위해 8자리마다 공백추가
        printf("%d", (dec >> (i-1)) & 0x01);
    }
    return 0; 
}

출력결과
12 --> 00000000 00000000 00000000 00001100
-12 --> 11111111 11111111 11111111 11110100

geneven의 이미지

aniseeker wrote:
질문과는 관련없는 내용이지만..

이 친절함은 정말이지 대한민국 만세로군요. (^-^)b

모두 복받으실 겁니다.

답주신 분들 정말 감사하고요. 복받으세요

pynoos의 이미지

다 끝난 것이긴하지만...

폐인모드로.. 코드를 작성해보면.. 7489324 에대한 이진수는..

$ cat a.c

main(_,o,O)
{
        int x = 7489324;
        _-- && main(0, 1<<31, x);
        O = x & o;
        o ? printf("%c", "10"[!O]) && main( 0, (unsigned)o >> 1) : exit(0);
}

C 컴파일러로만 됩니다.

h2h1995의 이미지

제가 예전에 vc++로 만들어놓은 소스입니다.

http://tcltk.co.kr/phpBB2/viewtopic.php?t=137

tcl/tk 의 확장패키지로 만들어 놓은것이니..
바로사용은 불가능하구요..
안에 vc++용 소스가 있으니.. 필요한 부분만 카피해서 쓰시면 됩니다.
2진수 <-> 10진수 <-> 16진수 상호변환을 해주고, 메모리가 허락하는한 아무리 큰수도 변환해줍니다.

----------------
http://tcltk.co.kr

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.