Created
July 10, 2025 21:14
-
-
Save denwarenjii/66cc73f5c08b718f4bcbab2fe77791b1 to your computer and use it in GitHub Desktop.
Print bytes in binary C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <inttypes.h> | |
/* Credit to https://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format */ | |
#define BYTE_TO_BIN_FORMAT "%c%c%c%c%c%c%c%c" | |
#define BYTE_TO_BIN(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') | |
#define LITTLE_ENDIAN 0 | |
#define BIG_ENDIAN 1 | |
void print_bin(const void *data, const size_t size, const uint8_t endianness) { | |
printf("data: 0b"); | |
const uint8_t *bytes = (const uint8_t *)data; | |
for (size_t i = 0, idx = i; i < size; i++ ) { | |
if (endianness == BIG_ENDIAN) { | |
/* Reverse byte order */ | |
idx = size - i - 1; | |
} else { | |
idx = i; | |
} | |
printf(BYTE_TO_BIN_FORMAT, BYTE_TO_BIN(bytes[idx])); | |
if (i < size - 1) { | |
/* Seperate each byte when printing */ | |
printf(" "); | |
} | |
} | |
printf("\n"); | |
} | |
int main(void) { | |
/* 0xAA = 0b10101010 */ | |
uint32_t a = 0x00AA00AA; | |
printf("[Little endian] "); | |
print_bin(&a, sizeof(uint32_t), LITTLE_ENDIAN); | |
printf("[Big endian] "); | |
print_bin(&a, sizeof(uint32_t), BIG_ENDIAN); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment