For data of types such as int
, char
, you could just print them with "%x" to get their binary representations. But floating point number is different, you usually need an union at here. For example, to get the binary representation of 1.2
as a double, you could do something like:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
union {
double number;
unsigned char bytes[sizeof(double)];
} double_bytes;
double_bytes.number = 1.2;
for (size_t i = 0; i < sizeof(double); i++) {
printf("%x ", double_bytes.bytes[i]);
}
printf("\n");
exit(EXIT_SUCCESS);
}
This version also include the binary representation, which sometimes is harder to understand than hexadecimal:
#include <stdio.h>
#include <stdlib.h>
char *
byte2bin(char buf[10], unsigned char ch)
{
char *bins[] = {
"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111",
};
sprintf(buf, "%s %s", bins[(ch & 0xf0)>>4], bins[ch & 0xf]);
return buf;
}
int
main(int argc, char *argv[])
{
union {
double number;
unsigned char bytes[sizeof(double)];
} double_bytes;
double_bytes.number = 1.2;
for (size_t i = 0; i < sizeof(double); i++) {
printf("%x ", (unsigned int)double_bytes.bytes[i] & 0xff);
}
printf("\n");
for (size_t i = 0; i< sizeof(double); i++) {
char buf[10] = { '\0' };
printf("%s ", byte2bin(buf, double_bytes.bytes[i]));
}
printf("\n");
exit(EXIT_SUCCESS);
}
Compiled with GCC 4.7.2: gcc -std=c99
Output:
$ ./a.out
33 33 33 33 33 33 f3 3f
0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 1111 0011 0011 1111
I believe those spaces in the output made it a little bit easier for human eyes and minds.