How do I get bit-by-bit data from an integer value in C?

后端 未结 8 1118
时光说笑
时光说笑 2020-11-30 17:36

I want to extract bits of a decimal number.

For example, 7 is binary 0111, and I want to get 0 1 1 1 all bits stored in bool. How can I do so?

OK, a loop is

8条回答
  •  误落风尘
    2020-11-30 17:38

    If you don't want any loops, you'll have to write it out:

    #include 
    #include 
    
    int main(void)
    {
        int num = 7;
    
        #if 0
            bool arr[4] = { (num&1) ?true: false, (num&2) ?true: false, (num&4) ?true: false, (num&8) ?true: false };
        #else
            #define BTB(v,i) ((v) & (1u << (i))) ? true : false
            bool arr[4] = { BTB(num,0), BTB(num,1), BTB(num,2), BTB(num,3)};
            #undef BTB
        #endif
    
        printf("%d %d %d %d\n", arr[3], arr[2], arr[1], arr[0]);
    
        return 0;
    }
    

    As demonstrated here, this also works in an initializer.

提交回复
热议问题