tomermes
tomermes

Reputation: 23360

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

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

Upvotes: 1

Views: 2197

Answers (4)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215221

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

Upvotes: 2

ruslik
ruslik

Reputation: 14870

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.

Upvotes: 2

Joey Adams
Joey Adams

Reputation: 43380

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

Upvotes: 1

Paulo Santos
Paulo Santos

Reputation: 11567

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

Upvotes: 1

Related Questions