C printing bits

前端 未结 5 1833
死守一世寂寞
死守一世寂寞 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.

提交回复
热议问题