Reputation: 660
I am trying to convert an unsigned long to binary in C.
char* long_to_binary(unsigned long k)
{
static char c[65];
c[0] = '\0';
unsigned long val;
for (val = ULONG_MAX; val > 0; val >>= 1)
{
strcat(c, ((k & val) == val) ? "1" : "0");
}
return c;
}
What am I doing wrong here? It prints out the incorrect values. I tried printing out val
and instead of printing the base2 values are off by one. So it prints like 3 7 15 ....
I tried initialising the value to ULONG_MAX+1 instead of ULONG_MAX but then it doesn't even enter the loop.
Any ideas why this is happening?
Thanks in advance!
Upvotes: 1
Views: 6752
Reputation: 223917
You're initializing val
to have all bits set. So when you apply the &
, the result of the comparison will be false unless k
has all bits set.
You only want one bit set in val
, and you need to start with the highest bit. So initialize it like this:
for (val = 1UL << (sizeof(unsigned long)*8-1); val > 0; val >>= 1) {
Then when you call it like this:
printf("binary=%s\n",long_to_binary(0x12345678));
You get this:
binary=0000000000000000000000000000000000010010001101000101011001111000
Upvotes: 3