Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophejunke/277fea96cddd5b263f58c4a957415946 to your computer and use it in GitHub Desktop.
Save christophejunke/277fea96cddd5b263f58c4a957415946 to your computer and use it in GitHub Desktop.
Check width
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
/* PARAMETERS */
/* Upper bound of loop (inclusive) */
const unsigned int upper_bound = 12;
/* width is the minimal length of the outputted binary number
* (no truncation, it can be bigger). */
const unsigned int width = 56;
/* Padding character. */
const char padchar = '-';
/* ITERATING AND PRINTING */
const int bitcount = (8 * sizeof(unsigned int));
const int extraneous = width - bitcount;
/* Bits below width_threshold should be left-padded. */
const unsigned int width_threshold =
(extraneous < 0) ? (1 << width) : -1;
/* 111...111
^ 011...111
-----------
100...000 */
const unsigned int largest = -1;
const unsigned int bitmask_max = largest ^ (largest >> 1) ;
unsigned int i = 0;
for(i = 0; i <= upper_bound; ++i) {
unsigned int mask;
/* Did we encounter only zeros so far? */
bool only_zeroes = true;
/* Pad the extraneous bits */
int j;
for(j = 0; j < extraneous; ++j) {
putchar(padchar);
}
/* Loop over bits from the most-significand ones to the least */
for(mask = bitmask_max; mask > 0; mask >>= 1) {
const bool bit = (i & mask);
only_zeroes &= !bit;
if (only_zeroes && mask >= width_threshold) {
/* Only zeroes so far, no padding yet */
continue;
}
putchar(bit
? '1'
/* "mask > 1" ensures i == 0 is
* printed as '0', not as padchar */
: ((only_zeroes && mask > 1)
? padchar
: '0'));
}
putchar('\n');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment