Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a printf converter to print in binary format?

Tags:

c

printf

I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?

I am running gcc.

printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n" print("%b\n", 10); // prints "%b\n" 
like image 310
Brian Avatar asked Sep 21 '08 20:09

Brian


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 %U in printf?

Unsigned Integer Format Specifier %u The %u format specifier is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in the memory. It is used within the printf() function for printing the unsigned integer variable.

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 I convert decimal to binary?

Take decimal number as dividend. Divide this number by 2 (2 is base of binary so divisor here). Store the remainder in an array (it will be either 0 or 1 because of divisor 2). Repeat the above two steps until the number is greater than zero.


1 Answers

Hacky but works for me:

#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" #define BYTE_TO_BINARY(byte)  \   (byte & 0x80 ? '1' : '0'), \   (byte & 0x40 ? '1' : '0'), \   (byte & 0x20 ? '1' : '0'), \   (byte & 0x10 ? '1' : '0'), \   (byte & 0x08 ? '1' : '0'), \   (byte & 0x04 ? '1' : '0'), \   (byte & 0x02 ? '1' : '0'), \   (byte & 0x01 ? '1' : '0')  
printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte)); 

For multi-byte types

printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n",   BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m)); 

You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to BYTE_TO_BINARY) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.

like image 124
William Whyte Avatar answered Sep 28 '22 05:09

William Whyte