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.
Asked
Active
Viewed 2.5k times
5
PC Luddite
- 5,761
- 6
- 22
- 39
Frank Tocci
- 586
- 2
- 7
- 18
-
See this post http://stackoverflow.com/questions/35641213/printing-binary-number-giving-weird-results – machine_1 Mar 10 '16 at 21:03
3 Answers
11
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.
PC Luddite
- 5,761
- 6
- 22
- 39
-
The loop `for(; i > 0; --i) {` is wrong; for 32 bit ints it will start at 32. my suggestion: `while i--) {` – wildplasser Mar 12 '16 at 19:04
-
2
There isn't one. If you want to output in binary, just write code to do it.
David Schwartz
- 173,634
- 17
- 200
- 267
-
2
-
1It completely answers his question. If a complete answer should be a comment, then it's a bad question. But I don't see anything wrong with the question. – David Schwartz Mar 10 '16 at 21:16
0
There is no direct way. One way, you could make a look-up table that converts a byte to a const char * of 1's and 0's. Then you could iterate through the bytes and print out what is in the look-up table.
Russley Shaw
- 441
- 2
- 9