Printing binary representation of a char in C

binary, c, char, printing

Solution

What you'd want to do is use bitwise operators to mask the bits one by one and print them to the standard output.

- A `char` in C is guaranteed to be 1 byte, so loop to `8`.

- Within each iteration, mask off the highest order bit.

- Once you have it, just print it to standard output.

Here is a quick stab which hopefully makes sense...

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

  return 0;
}

CodePad.

In order to get the bit, I shift to the left to get the numbered bit (highest to lowest so printing it is easy) and then mask it off. I then translate it to `0` or `1` with `!!`.

Problem

I want a really basic way to print out the binary representation of a char. I can't seem to find any example code anywhere. I assumed you could do it in a few lines but everything I find is overly long and complex using lots of functions I haven't used before. `atoi` comes up a lot but it's not standard. Is there a simple function or simple way of writing a function to take a char variable and then print out a binary representation? Eg: char 'x' is the argument taken in by the function and "x is 0111 1000" is printed out. It's for a school assignment where I must take user input of a string and print out the string in binary. I just need to get the basics of converting a char to binary but i'm struggling at the moment.

Original source

Related problems