1

For example, 6 => [1,1,0]

Paul R
  • 208,748
  • 37
  • 389
  • 560
tomermes
  • 22,950
  • 16
  • 43
  • 67

4 Answers4

2

To read bits you can use

char get_bit(unsigned int n, int bit_num){
    if (bit_num < 0 || bit_num >= sizeof(int) * CHAR_BIT)
        return -1;
    return (n >> bit_num) & 1;
};

Its main problem is that it's not fast, but OP didn't even specified if he wanted numers or digits.

ruslik
  • 14,714
  • 1
  • 39
  • 40
  • I like this answer: nice and simple, and probably even optimizes into a native bit test instruction. However, a few little nitpicks: 1.) `char` is unsigned on some architectures, so returning `-1` would likely yield `255` on those architectures, 2.) Returning a `char` usually isn't much better than returning an `int` due to C's tendency to promote things, and 3.) If I were me, I'd probably just `assert(bit_num >= 0 && bit_num < sizeof(unsigned int) * CHAR_BIT);` rather than having to document the "garbage out" when there is "garbage in". – Joey Adams Dec 07 '10 at 18:08
  • @Joey: well, it's a sample for a programmer that will use and refractor the code according to his/her needs, and not to be put into library :) – ruslik Dec 07 '10 at 18:14
2
unsigned x = number;
char buf[sizeof(int)*CHAR_BIT+1], *p=buf+sizeof(buf);
for (*--p=0; x; x>>=1) *--p='0'+x%2;
R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
1

I don't know but I'd make something like

int[32] bits = {};
int     value = 255;
int     i = 0;

while (value)   
{
  bits[i++] = value & 1;
  value = value >> 1;
}
Paulo Santos
  • 11,285
  • 4
  • 39
  • 65
1

A simple and fast way is to use an unsigned integer as a "cursor" and shift it to advance the cursor:

1000000000000000
0100000000000000
0010000000000000
0001000000000000
0000100000000000
0000010000000000
0000001000000000
0000000100000000
...

At each iteration, use bitwise & to see if the number and the cursor share any bits in common.

A simple implementation:

// number of bits in an unsigned int
#define BIT_COUNT (CHAR_BIT * sizeof(unsigned int))

void toBits(unsigned int n, int bits[BIT_COUNT])
{
    unsigned int cursor = (unsigned int)1 << (BIT_COUNT - 1);
    unsigned int i;

    for (i = 0; i < BIT_COUNT; i++, cursor >>= 1)
        out[i++] = (n & cursor) ? 1 : 0;
}
Joey Adams
  • 41,996
  • 18
  • 86
  • 115