Last active
August 24, 2020 20:10
-
-
Save jstaursky/6e3b007e0a0dd818b6e5bb5b0bf7c0f1 to your computer and use it in GitHub Desktop.
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 "stdlib.h" | |
#include "string.h" | |
#include "stdint.h" | |
void print_bits(uintmax_t number) | |
{ | |
unsigned char* output = calloc (8*sizeof (uintmax_t), 1); | |
unsigned char* mov = output; | |
// Test bits found in "number" from LSB to MSB. | |
for (uintmax_t nbit = 8 * sizeof (uintmax_t); nbit-- != 0; ++mov) { | |
if ((number & ((uintmax_t)1 << nbit)) != 0) | |
*mov = '1'; | |
else | |
*mov = '0'; | |
} | |
// print in binary. | |
mov = output; | |
while (printf ("%c", *mov++), *mov) { | |
if ((mov - output) % 32 == 0) | |
printf (" | "); | |
else if ((mov - output) % 8 == 0) { | |
printf (" "); | |
} | |
} | |
printf ("\n"); | |
// print in hex. | |
mov = ((unsigned char*)&number + sizeof(number) - 1); | |
do { | |
printf ("%4s0x%02x ","", (unsigned int)*mov); | |
if ((mov - (unsigned char*)&number) == sizeof(number)/2) | |
printf ("| "); | |
} while ((mov-- - (unsigned char*)&number) != 0); | |
printf("\n"); | |
free (output); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment