store binary of decimal in char array

Jun 25, 2015 at 11:54am
i want to store binary equivalent of decimal number in char array by applying below code, but the problem is i'm not able to hold the last bit of the decimal number. I am getting garbage values

1
2
3
4
5
6
7
8
9
10
11
12
   int k,j;
  char c[40];
  j=32;
while(k)
    {    
     k=k>>1;
     c[j]=k|1;
     j--;
     }

     puts("number is");
     puts(c);
Jun 25, 2015 at 11:56am
Whad do you exactly want? Store each bit in own character, or store each byte in own character (which exactly the size of byte)?
Jun 25, 2015 at 12:03pm
what i want to convert a decimal to its binary equivalent and store in a char array
the size of byte should be 4(int) bytes
Jun 25, 2015 at 12:12pm
What you want to see if you output your char arry? String of 0s and 1s or 4 characters (possibly invisible) with values corresponding to individual byte of integer?
Jun 25, 2015 at 12:22pm
yes , string of 0s and 1s
Jun 25, 2015 at 12:43pm
1
2
3
4
char line[33];
unsigned  number = 1023;
itoa(number, line, 2);
puts(line);
Jun 25, 2015 at 12:57pm
thnks

if i have to do with shift operator, then shouldn't i use '0' with char array
Jun 25, 2015 at 1:00pm
Yes. Integer 0 and chracter '0' are different. integer 0 is used to denote end of string.
Topic archived. No new replies allowed.