In accordance with the request, I decided to extend my comment on the index finger to a complete answer. Although his answer is correct, he is overly complex. In addition, all current answers use a signed int to represent the values. This is dangerous, since shifting negative values ββaccording to the implementation (i.e. Not portable) and shifting to the left can lead to undefined behavior (see this question ).
By right shifting the desired bit to the least significant bit position, masking can be done with 1 . There is no need to calculate a new mask value for each bit.
(n >> k) & 1
As a complete program, the calculation (and subsequent printing) of an array of one-bit values:
#include <stdio.h> #include <stdlib.h> 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 the bits, as in this case, and not a specific one, the cycle can be further changed to
for(bit = 0; bit < n_bits; ++bit, input >>= 1) bits[bit] = input & 1;
This changes the input in place and thus allows the use of a constant width, single-bit shift, which may be more efficient for some architectures.
Joe Oct 07 '14 at 7:16 2014-10-07 07:16
source share