Last active
September 2, 2018 01:49
-
-
Save leptos-null/5fb101f937bad5e2bcb6bee7337671df to your computer and use it in GitHub Desktop.
Three macros for printing the bit representation of a fixed-point value
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <limits.h> | |
/* prints each character representation of the byte one at a time. | |
* no memory management required; slower, than using a buffer. | |
*/ | |
#define printBitRepresentationEach(a) \ | |
({ \ | |
for (size_t _i = (sizeof(a) * CHAR_BIT); _i; _i--) { \ | |
putchar((a & (1 << (_i - 1))) ? '1' : '0'); \ | |
} \ | |
putchar('\n'); \ | |
}) | |
/* prints a stack-buffer of characters. | |
* fast, but can go through stack memory quickly. | |
*/ | |
#define printBitRepresentationBuff(a) \ | |
({ \ | |
size_t _i = sizeof(a) * CHAR_BIT; \ | |
char _buff[_i + 1]; \ | |
char *_buff_p = _buff; \ | |
for (; _i; _i--) { \ | |
*(_buff_p++) = (a & (1 << (_i - 1))) ? '1' : '0'; \ | |
} \ | |
*_buff_p = '\0'; \ | |
puts(_buff); \ | |
}) | |
/* prints a heap-buffer of characters. | |
* very tight memory management. malloc is not optimal for all uses | |
*/ | |
#define printBitRepresentationAlloc(a) \ | |
({ \ | |
size_t _i = sizeof(a) * CHAR_BIT; \ | |
char *_buff = malloc(_i + 1); \ | |
char *_buff_p = _buff; \ | |
for (; _i; _i--) { \ | |
*(_buff_p++) = (a & (1 << (_i - 1))) ? '1' : '0'; \ | |
} \ | |
*_buff_p = '\0'; \ | |
puts(_buff); \ | |
free(_buff); \ | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment