开发者

What is the fastest way of converting an int to a binary representation in C?

Fo开发者_开发知识库r example, 6 => [1,1,0]


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.


unsigned x = number;
char buf[sizeof(int)*CHAR_BIT+1], *p=buf+sizeof(buf);
for (*--p=0; x; x>>=1) *--p='0'+x%2;


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;
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜