0

The program I am trying to make asks the user for a number, displays that number in binary, and then reverses the order that the bits in the binary number are displayed in.

For instance, if I enter the number 1, the output is displayed as 00000001, and the reverse of that would be printed as 10000000. I have been able to get the number to convert to binary, but I'm not sure how to get the reverse output.

Any suggestions? I have provided my code below so that I can show where I am at in this program.

void print_bits(unsigned char x) {

   int i = 0;

   for (i = 7; i >= 0; i--) {       
     printf("%d", (x & (1 << i)) >> i);
   }    

   printf("\n");    
}

int main(int argc, char * argv[]) {

  unsigned char x;

  printf("Enter a number: ");

  scanf("%hhu", &x);
  printf("Bits: ");
  print_bits(x);

  return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115

1 Answers1

0

Just do the opposit for loop when printing:

for (i = 0; i <= 7; i++) {
    printf("%d", (x & (1 << i)) >> i);
}
Franco Pan
  • 128
  • 2
  • 11