Possible Duplicate:
Is there a printf converter to print in binary format?
Here is my program
#include<stdio.h> int main () { int i,a=2; i=~a; printf("a=%d\ni=%d\n",a,i); return 0; }
The output is
a=2 i=-3
I want this to print in binary. There are %x, %o, and %d which are for hexadecimal, octal, and decimal number, but what is for printing binary in printf?
To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.
There isn't one. If you want to output in binary, just write code to do it.
In C++, we can use Bitwise Operators to convert the given decimal to a binary number. Bitset class in C++ can be used to store the binary values 0 or 1. In C++, the size of the bitset class is fixed at compile time determined by the template parameter.
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) { if (n & 1) printf("1"); else printf("0"); n >>= 1; } printf("\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With