Skip to content

Instantly share code, notes, and snippets.

@zeddee
Created November 8, 2025 12:11
Show Gist options
  • Select an option

  • Save zeddee/1a3f33415da24190023904017d15e783 to your computer and use it in GitHub Desktop.

Select an option

Save zeddee/1a3f33415da24190023904017d15e783 to your computer and use it in GitHub Desktop.
rudimentary bit printer
#ifndef PRINT_BITS_C
#define PRINT_BITS_C
#include <stdio.h>
#include <limits.h>
extern void print_bits(unsigned bits)
{
int WIDTH = sizeof(bits) * CHAR_BIT;
char bit_repr[WIDTH];
for (int i = 0; i <= WIDTH - 1; i++)
{
bit_repr[i] = bits & 0x01; // Read the last bit by masking it
bits = bits >> 1;
}
for (int i = WIDTH - 1; i >= 0; i--)
{
if (i == 0) {
printf("%i\n", bit_repr[i]);
break;
} else if ((i % 3) == 0){ // octal-friendly representation
printf("%i ", bit_repr[i]);
} else {
printf("%i", bit_repr[i]);
}
}
}
#endif /* !PRINT_BITS_C */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment