Skip to content

Instantly share code, notes, and snippets.

@Septien
Created August 17, 2021 20:58
Show Gist options
  • Select an option

  • Save Septien/94a1912ff782f762085aef65366951f2 to your computer and use it in GitHub Desktop.

Select an option

Save Septien/94a1912ff782f762085aef65366951f2 to your computer and use it in GitHub Desktop.
A set of macros to print an integer (8, 16, 32, and 64 bits) in its bit representation. See code for reference.
/*
* Print the binary representation of an integer (8, 16, 32, and 64).
* Based on the answers from William Whyte and ideasman42 at stackoverflow:
* https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
*/
// 8-bit integer
#define BYTE_TO_BINARY_PATTERN_INT8 "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY_INT8(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')
// 16-bit integer
#define BYTE_TO_BINARY_PATTERN_INT16 \
BYTE_TO_BINARY_PATTERN_INT8 BYTE_TO_BINARY_PATTERN_INT8
#define BYTE_TO_BINARY_INT16(bytes) \
BYTE_TO_BINARY_INT8((bytes) >> 8) BYTE_TO_BINARY_INT8((bytes))
// 32-bit integer
#define BYTE_TO_BINARY_PATTERN_INT32 \
BYTE_TO_BINARY_PATTERN_INT16 BYTE_TO_BINARY_PATTERN_INT16
#define BYTE_TO_BINARY_INT32(bytes) \
BYTE_TO_BINARY_INT16((bytes) >> 16) BYTE_TO_BINARY_INT16((bytes))
// 64-bit integer
#define BYTE_TO_BINARY_PATTERN_INT64 \
BYTE_TO_BINARY_PATTERN_INT32 BYTE_TO_BINARY_PATTERN_INT32
#define BYTE_TO_BINARY_INT64(bytes) \
BYTE_TO_BINARY_INT32((bytes) >> 32) BYTE_TO_BINARY_INT32((bytes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment