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

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

    As requested, I decided to extend my comment on forefinger's answer to a full-fledged answer. Although his answer is correct, it is needlessly complex. Furthermore all current answers use signed ints to represent the values. This is dangerous, as right-shifting of negative values is implementation-defined (i.e. not portable) and left-shifting can lead to undefined behavior (see this question).

    By right-shifting the desired bit into the least significant bit position, masking can be done with 1. No need to compute a new mask value for each bit.

    (n >> k) & 1
    

    As a complete program, computing (and subsequently printing) an array of single bit values:

    #include 
    #include 
    
    int main(int argc, char** argv)
    {
        unsigned
            input = 0b0111u,
            n_bits = 4u,
            *bits = (unsigned*)malloc(sizeof(unsigned) * n_bits),
            bit = 0;
    
        for(bit = 0; bit < n_bits; ++bit)
            bits[bit] = (input >> bit) & 1;
    
        for(bit = n_bits; bit--;)
            printf("%u", bits[bit]);
        printf("\n");
    
        free(bits);
    }
    

    Assuming that you want to calculate all bits as in this case, and not a specific one, the loop can be further changed to

    for(bit = 0; bit < n_bits; ++bit, input >>= 1)
        bits[bit] = input & 1;
    

    This modifies input in place and thereby allows the use of a constant width, single-bit shift, which may be more efficient on some architectures.

提交回复
热议问题