14

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.

alex
  • 479,566
  • 201
  • 878
  • 984
user1783150
  • 281
  • 2
  • 6
  • 13

4 Answers4

25

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 !!.

alex
  • 479,566
  • 201
  • 878
  • 984
  • This is perfect, exactly what I've been looking for! I'll read up on masking the shift operators so I can understand it fully. If you have the time though could you explain what "mask of the highest order bit means". With my currently knowledge I'm not 100% sure what's happening on the main line inside the for loop. Thanks! – user1783150 Aug 20 '13 at 06:20
  • @user1783150 The high order bit is the 7th bit, e.g. the `1` in `1000000`(also the number `0x80` or `128`). – alex Aug 20 '13 at 06:37
  • I'm still a bit curious about how the "!!" operator works? Does it convert any positive number to a "1" and keep 0 as "0"? A google of '"!!" operator C' hasn't been returning any results to be honest. Is it not a standard operator? – user1783150 Aug 22 '13 at 00:22
  • 4
    @user1783150 It's not the `!!` operator, it's two `!` operators. A `!` negates a value, returning either `0` or `1`. Two of them flips it twice, effectively used for its side effect or turning the value into its `0` or `1` equivalent. – alex Aug 22 '13 at 00:40
  • @alex but why do we need to flip twice? – Zingam Jun 16 '14 at 16:39
  • @Zingam Otherwise you'd get the opposite value, which isn't what you'd want. – alex Jun 17 '14 at 01:57
  • @alex That I a understand... Well, I actually got your idea finally! It was simple than expected. Thanx! – Zingam Jun 17 '14 at 08:35
  • @alex I think you made a small typo in your second comment, referring to the 6th bit as the 7th. I think you meant to say `1` in `10000000`, not `1` in `1000000` (we must add an extra `0`) – Chrisuu Oct 08 '21 at 00:18
2

you can use this method

const char *byte_to_binary(int x)
{
    static char b[9];
    b[0] = '\0';

    int z;
    for (z = 128; z > 0; z >>= 1)
    {
        strcat(b, ((x & z) == z) ? "1" : "0");
    }

    return b;
}

to get the binary representation and print with it

for example

 printf("%s\n", byte_to_binary(15));
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
2
void printBits(size_t const size, void const * const ptr)
{
    unsigned char *b = (unsigned char*) ptr;
    unsigned char byte;
    int i, j;

    for (i=size-1;i>=0;i--)
    {
        for (j=7;j>=0;j--)
        {
            byte = b[i] & (1<<j);
            byte >>= j;
            printf("%u", byte);
        }
    }
    puts("");
}

int main(int argv, char* argc[])
{
        int i = 23;
        uint ui = UINT_MAX;
        float f = 23.45f;
        printBits(sizeof(i), &i);
        printBits(sizeof(ui), &ui);
        printBits(sizeof(f), &f);
        return 0;
}
Optimus Prime
  • 6,817
  • 5
  • 32
  • 60
1

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;
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331