C printing bits

前端 未结 5 1824
死守一世寂寞
死守一世寂寞 2020-12-03 15:14

I am trying to write a program in C that prints bits of int. for some reason i get wrong values,

void printBits(unsigned int num){
    unsigned int size = si         


        
相关标签:
5条回答
  • 2020-12-03 15:19

    How about this Macro:

    #define print_bits(x) \
    do { \
            unsigned long long a__ = (x); \
            size_t bits__ = sizeof(x) * 8; \
            printf(#x ": "); \
            while(bits__--) putchar(a__ & (1 << bits__) ? '1' : '0'); \
            putchar('\n'); \
    } while(0)
    

    Use like:

    char c = 3;
    int i = -1;
    print_bits(c);
    print_bits(i);
    

    output:

    c: 00000011
    i: 11111111111111111111111111111111
    

    If you don't want to print the expression 'x' which is the argument to 'print_bits' remove the line:

    printf(#x ": "); \
    

    This Marco can be used on any primitive datatype and the expression 'x' will be evaluated only once. So you should be safe from side effects.

    0 讨论(0)
  • 2020-12-03 15:28

    You are calculating the result correctly, but you are not printing it right. Also you do not need a second loop:

    for(;i<size*8;++i){
        // print last bit and shift left.
        printf("%u ",num&maxPow ? 1 : 0);
        num = num<<1;
    }
    

    If you'd like to show off, you could replace the conditional with two exclamation points:

    printf("%u ", !!(num&maxPow));
    
    0 讨论(0)
  • 2020-12-03 15:29

    The result you get is because num&maxPow is either 0 or maxPow. To print 1 instead of maxPow, you could use printf("%u ", num&maxPow ? 1 : 0);. An alternative way to print the bits is

    while(maxPow){
        printf("%u ", num&maxPow ? 1 : 0);
        maxPow >>= 1;
    }
    

    i.e. shifting the bitmask right instead of num left. The loop ends when the set bit of the mask gets shifted out.

    0 讨论(0)
  • 2020-12-03 15:33

    To address point two, I'd consider the following, which is simplified a bit for ease of understanding.

    void printBits(unsigned int num)
    {
       for(int bit=0;bit<(sizeof(unsigned int) * 8); bit++)
       {
          printf("%i ", num & 0x01);
          num = num >> 1;
       }
    }
    
    0 讨论(0)
  • 2020-12-03 15:34
    void print_bits(unsigned int x)
    {
        int i;
        for(i=8*sizeof(x)-1; i>=0; i--) {
            (x & (1 << i)) ? putchar('1') : putchar('0');
        }
        printf("\n");
    }
    
    0 讨论(0)
提交回复
热议问题