In addition to simply creating a binary string, it is sometimes useful to specify the length of the resulting string for comparison or reading purposes. The next small function will take a number and a length (the number of digits in a binary field) and provide this as a character to use or print. With a little more effort, you can also split the sting into formatted sections. (e.g., 16 digits: 0034-4843-2392-6720)
Try the following:
#include <stdio.h>
#include <stdlib.h>
#if defined(__LP64__) || defined(_LP64)
# define BUILD_64 1
#endif
#ifdef BUILD_64
# define BITS_PER_LONG 64
#else
# define BITS_PER_LONG 32
#endif
char *binpad (unsigned long n, size_t sz);
int main (int argc, char **argv) {
int n = argc > 1 ? atoi (argv[1]) : 251;
size_t sz = argc > 2 ? (size_t) atoi (argv[2]) : 8;
printf ("\n %8d : %s\n\n", n, binpad (n, sz));
return 0;
}
char *binpad (unsigned long n, size_t sz)
{
static char s[BITS_PER_LONG + 1] = {0};
char *p = s + BITS_PER_LONG;
register size_t i;
for (i = 0; i < sz; i++)
*--p = (n>>i & 1) ? '1' : '0';
return p;
}
Exit
$ binprnex
251 : 11111011
$ binprnex 42869 16
42869 : 1010011101110101
source
share