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);
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: