Created
July 2, 2014 14:02
-
-
Save mickm/282608229c7a54bbc464 to your computer and use it in GitHub Desktop.
bits
This file contains 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
/* | |
* bits - pretty-print bits from a hex/dec/oct input | |
* | |
* cc -ansi -pedantic -Wall -o bits bits.c | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
#include <stdint.h> | |
#define BITSIZE(n) (CHAR_BIT*sizeof(n)) | |
#define BITVALUE(n, bit) ((n & (1UL<<bit)) == 0 ? 0 : 1) | |
#define BITS_PER_LINE (CHAR_BIT*2) | |
#define NUM_LINES(n) (BITSIZE(n)*1.0/BITS_PER_LINE) | |
int main(int argc, char *argv[]) | |
{ | |
uint32_t number; | |
int bit, line, a, b; | |
if (argc != 2) { | |
fprintf(stderr, "bits - pretty print bits from a hex/dec/oct input\n\n"); | |
fprintf(stderr, "usage: bits number\n"); | |
return 0; | |
} | |
number = strtoul(argv[1], NULL, 0); | |
printf("input: %s\n", argv[1]); | |
printf("decimal unsigned: %u\n", (int32_t)number); | |
printf("decimal signed: %d\n", number); | |
printf("hex: 0x%08x\n", number); | |
printf("binary: 0b"); | |
for (bit = BITSIZE(number); bit-- > 0; ) { | |
printf("%u", BITVALUE(number, bit)); | |
} | |
printf("\n"); | |
printf("bits:\n\n"); | |
for (line = 0; line < NUM_LINES(number); line++) { | |
a = BITSIZE(number) - (line*BITS_PER_LINE); | |
b = a - BITS_PER_LINE; | |
b = b < 0 ? 0 : b; | |
for (bit = a; bit-- > b; ) { | |
printf("%3u", bit); | |
} | |
printf("\n"); | |
for (bit = a; bit-- > b; ) { | |
printf("%3u", BITVALUE(number, bit)); | |
} | |
printf("\n\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment