Mantorok said:
Is it possible to display the underlying representation of integers?
Not just integers but also float/double and is it also possible to
display the padding bits of signed integer types in standard C?
/* BEGIN bitstr.c */
#include <stdio.h>
#include <limits.h>
typedef float e_type;
#define STRING "%s = %f\n"
char *bitstr(char *, void const *, size_t);
int main(void)
{
e_type f, d;
char fbits[CHAR_BIT * sizeof f + 1], *s;
s = STRING;
for (f = 0.2f; 0.75 > f; f += 0.125) {
bitstr(fbits, &f, sizeof f);
printf(s, fbits, f);
}
for (d = 2; 20000 > d; d *= 2) {
for (f = d - 1; 0.75 > f - d; f += 0.5) {
bitstr(fbits, &f, sizeof f);
printf(s, fbits, f);
}
}
return 0;
}
char *bitstr(char *str, const void *obj, size_t n)
{
unsigned char mask;
const unsigned char *byte = obj;
char *const ptr = str;
while (n--) {
mask = ((unsigned char)-1 >> 1) + 1;
do {
*str++ = (char)(mask & byte[n] ? '1' : '0');
mask >>= 1;
} while (mask);
}
*str = '\0';
return ptr;
}
/* END bitstr.c */