Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the format specifier for binary in C? [duplicate]

Tags:

c

symbols

binary

I have looked all over the place, but I have not found an answer to my question. First of all, I know that the symbol for decimal is %d, the symbol for octal is %o, and the symbol for hexadecimal is %x. What I cannot find, however, is the symbol for binary. I would appreciate any help.

like image 259
Frank Tocci Avatar asked Mar 10 '16 20:03

Frank Tocci


2 Answers

The reason you're having trouble finding a format specifier for printing integers in binary is because there isn't one. You'll have to write you're own function to print numbers in binary.

So for a single unsigned byte:

#include <stdio.h>
#include <limits.h>

void print_bin(unsigned char byte)
{
    int i = CHAR_BIT; /* however many bits are in a byte on your platform */
    while(i--) {
        putchar('0' + ((byte >> i) & 1)); /* loop through and print the bits */
    }
}

And for a standard unsigned int:

#include <stdio.h>
#include <limits.h>

void print_bin(unsigned int integer)
{
    int i = CHAR_BIT * sizeof integer; /* however many bits are in an integer */
    while(i--) {
        putchar('0' + ((integer >> i) & 1)); 
    }
}

Adjust the function for larger integers accordingly. Be wary of signed shifting though because the behavior is undefined and entirely compiler dependent.

like image 92
PC Luddite Avatar answered Nov 12 '22 20:11

PC Luddite


There isn't one. If you want to output in binary, just write code to do it.

like image 44
David Schwartz Avatar answered Nov 12 '22 21:11

David Schwartz