Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing binary representation of a char in C [duplicate]

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.

like image 379
user1783150 Avatar asked Aug 20 '13 05:08

user1783150


2 Answers

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

  1. A char in C is guaranteed to be 1 byte, so loop to 8.
  2. Within each iteration, mask off the highest order bit.
  3. 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 !!.

like image 87
alex Avatar answered Oct 02 '22 19:10

alex


Try this:-

#include <limits.h>
char *chartobin ( unsigned char c )
{
    static char bin[CHAR_BIT + 1] = {0};
    int i;
    for( i = CHAR_BIT - 1; i >= 0; i-- )
    {
        bin[i] = (c % 2) + '0';
        c /= 2;
    }
   return bin;
}
like image 23
Rahul Tripathi Avatar answered Oct 02 '22 18:10

Rahul Tripathi