printf에서 2진법 형식지정자

조회수 18489회

제가 아는건 십진법, 팔진법, 십육진법 출력인데 이진법 형식지정자도 있을까요?

gcc를 쓰고 있고 밑에 코드처럼 쓸 수 있었으면 좋겠습니다

printf("%d %x %o\n", 10, 10, 10); //"10 A 12\n"
print("%b\n", 10); //"%b\n"

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    2진법 형식 지정자는 없기 때문에 직접 정의해서 써야 합니다.

    #include <stdio.h>      /* printf */
    #include <string.h>     /* strcat */
    #include <stdlib.h>     /* strtol */
    
    const char *byte_to_binary(int x)
    {
        static char b[9];
        b[0] = '\0';
    
        int z;
        for (z = 128; z > 0; z >>= 1)
        {
            strcat(b, ((x & z) == z) ? "1" : "0");
        }
        return b;
    }
    
    int main(void)
    {
        {
            /* 문자열에서 int로 */
            char *tmp;
            char *b = "0101";
    
            printf("%d\n", strtol(b, &tmp, 2));
        }
    
        {
            /* 바이트에서 문자열로 */
            printf("%s\n", byte_to_binary(5));
        }
    
        return 0;
    }
    

    또는

    //little endian으로 가정
    void printBits(size_t const size, void const * const ptr)
    {
        unsigned char *b = (unsigned char*) ptr;
        unsigned char byte;
        int i, j;
    
        for (i=size-1;i>=0;i--)
        {
            for (j=7;j>=0;j--)
            {
                byte = b[i] & (1<<j);
                byte >>= j;
                printf("%u", byte);
            }
        }
        puts("");
    }
    
    int main(int argv, char* argc[])
    {
            int i = 23;
            uint ui = UINT_MAX;
            float f = 23.45f;
            printBits(sizeof(i), &i);
            printBits(sizeof(ui), &ui);
            printBits(sizeof(f), &f);
            return 0;
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)