Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print binary number via printf [duplicate]

Tags:

c

printf

binary

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?

like image 467
Registered User Avatar asked Jun 16 '11 13:06

Registered User


People also ask

How do you print in binary format?

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.

What is the format specifier for binary in C?

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

How do you store binary numbers in C++?

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.


1 Answers

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"); 
like image 83
Vinicius Kamakura Avatar answered Sep 22 '22 23:09

Vinicius Kamakura