0

As a practice exercise I'm trying to convert an entered char value to binary and display each bit of the 8 bit output. I have found some example code for conversion:

int main (void)
{
char a =16;
int i=0;
for (i = 0; i < 8;i++) { 
printf("%d", !!((a << i) & 0x80));}
return 0;
}

however when I use an entered value for a such as with the code:

int main(void){
char a;
printf("Enter char value:", a);
scanf("%c", &a);
printf("a=%c", a);
return 0 ;}

the incorrect value is given. And also how would I be able to display each bit separately? for example

printf("The sign bit is %d\n", &);
printf("The bit 6 is %d\n", &);
printf("The bit 5 is %d\n", &);
printf("The bit 4 is %d\n", &);
printf("The bit 3 is %d\n", &);
printf("The bit 2 is %d\n", &);
printf("The bit 1 is %d\n", &);
printf("The bit 0 is %d\n", &);
Cœur
  • 37,241
  • 25
  • 195
  • 267
J.Smith
  • 11

1 Answers1

0

You could do a conversion doing math with the c code.. I did not click on the possible duplicate post but something like..

int i;
char c; 
int bits[8];
/*get a character from stdin and save it to c*/
i =  c + ‘0’;
if(i>=128){
    bits[7]=1;
     i= i-128;
}
if(i>=64){
    bits[6]=1;
    i = i - 64;
}
if(i >= 32){
    bits[5]=1;
    i =i- 32
}

// do this for all the bits

This should work and then you have bits[0] - bits[7] your 0-7 bits!! I am sure there is a better way to do this but this should work!!

Dustin177820
  • 111
  • 6
  • 1
    `i = c + ‘0’;` why?? It's wrong. Further - for this to work use `unsigned char` and also `int bits[8] = {0};` to get the array initialized. Correcting that may make this work but why not use a simple loop? – Support Ukraine Apr 25 '18 at 05:57