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

后端 未结 8 1120
时光说笑
时光说笑 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:46

    Here's one way to do it—there are many others:

    bool b[4];
    int v = 7;  // number to dissect
    
    for (int j = 0;  j < 4;  ++j)
       b [j] =  0 != (v & (1 << j));
    

    It is hard to understand why use of a loop is not desired, but it is easy enough to unroll the loop:

    bool b[4];
    int v = 7;  // number to dissect
    
    b [0] =  0 != (v & (1 << 0));
    b [1] =  0 != (v & (1 << 1));
    b [2] =  0 != (v & (1 << 2));
    b [3] =  0 != (v & (1 << 3));
    

    Or evaluating constant expressions in the last four statements:

    b [0] =  0 != (v & 1);
    b [1] =  0 != (v & 2);
    b [2] =  0 != (v & 4);
    b [3] =  0 != (v & 8);
    

提交回复
热议问题