Reputation: 99
I want to store binary equivalent of decimal number in char
array by applying below code, but the problem is I am not able to hold the last bit of the decimal number. I am getting garbage values.
int k,j;
char c[40];
j=32;
scanf("%d",&k);
while(k)
{
k=k>>1;
c[j]=k|1;
j--;
}
puts("number is");
puts(c);
Upvotes: 0
Views: 5099
Reputation: 23208
If interested, here is a slightly different method...
Consider that for a graphical binary representation of a 32 bit integer, you would need to contain 33 bytes: 32 for 1s and 0s, and 1 for string NULL terminator. As you walk through any 32 bit representation of an integer value, you can logical and (&
) the corresponding bit of 2^32 (2147483648) with each bit position of your input integer value to determine if that position should be a "1" or a "0", stacking the resultant character (ASCII) representations of 1
or 0
(48 or 49) as you go, into a string.
Here is the example to convert an integer into a 32 bit binary representation...
const char *byte_to_binary32(long x)
{
static char b[33]; // bits plus '\0'
b[0] = '\0';
char *p = b;
//unsigned long long z; required only if 64 bit conversion
unsigned long z;//this is sufficient for 32 bit conversion
for (z = 2147483648; z > 0; z >>= 1) //2^32
{
*p++ = (x & z) ? '1' : '0';
}
return b;
}
int main(void)
{
printf("Binary: %s\n\n", byte_to_binary32(100));
return 0;
}
Upvotes: 1
Reputation: 134286
I assume you want the lexicographical representation for the binary.
You need to take care of few things.
You must initialize k
before using. Ask for user input (or "hardcode", as we say) the value for k
.
If you want to use array c
as string, you need to null-terminate it.
You need to perform &
with a value of 1
to take out the last bit. Add that with '0'
(Remember, lexicographical). Store that.
Current array indexing will put you into trouble. You can use normal array indexing with j
, starting from 0
. After the loop, you need to null-terminate the last index and then go for printing.
A pseudo-code will look like
#include <stdio.h>
int main(void) {
int val = 16;
char bin [128] = {0};
int index = 0;
while(val)
{
bin[index] = '0' + (val&1u);
val = val >> 1;
index++;
}
bin[index] = 0;
puts(bin);
return 0;
}
NOTE: You may want to reverse the string before printing it.
Upvotes: 2
Reputation: 47915
Besides the problems noted by @SouravGhosh, you need to
(5) convert from the digits 0/1 to the character values for '0'
and '1'
by adding in the value of the character '0'
[actually Sourav noted that too], and
(6) pick off the low-order bit before shifting k
right by 1 bit.
Here's a working version:
char c[40];
int j=39;
c[j--]='\0';
while(k)
{
c[j]=(k&1)+'0';
j--;
k=k>>1;
}
puts("number is ");
puts(&c[j+1]);
Upvotes: 2