Created
December 28, 2011 21:21
-
-
Save Excedrin/1529801 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 <stdint.h> | |
#include <string.h> | |
#define CHAR_BIT 8 | |
#define MAXBITS (CHAR_BIT*sizeof(uintmax_t)) | |
#define FMT_BUF_SIZE (MAXBITS+1) | |
char *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE]) | |
{ | |
char *s = buf + FMT_BUF_SIZE; | |
memset(buf, '0', FMT_BUF_SIZE); | |
*--s = 0; | |
// printf("buf: %s", buf); | |
// if (!x) *--s = '0'; | |
for (; x; x/=2) *--s = '0' + x%2; | |
return buf; | |
} | |
uintmax_t createmask(int bits) { | |
uintmax_t x = ~0; | |
// why is GCC using a shift that respects sign bit on an unsigned variable? | |
if (bits) { | |
return x >> (MAXBITS - bits); | |
} else { | |
return 0; | |
} | |
} | |
uintmax_t buttface(int startbit, int endbit) { | |
return createmask(startbit - endbit) << endbit; | |
} | |
main() { | |
char buf[FMT_BUF_SIZE]; | |
uintmax_t m; | |
printf("%s\n", binary_fmt(buttface(4,2), buf)); | |
printf("%s\n", binary_fmt(buttface(64,32), buf)); | |
printf("%s\n", binary_fmt(buttface(7,3), buf)); | |
} | |
/* | |
% ./masks | |
0000000000000000000000000000000000000000000000000000000000001100 | |
1111111111111111111111111111111100000000000000000000000000000000 | |
0000000000000000000000000000000000000000000000000000000001111000 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment