I have a script that generates two random 32-bit floating point numbers a and b, and divides them to make an output c.
I would like to store all 3 of these floating point numbers in hexadecimal format, as a string that contains 8 characters.
I found a clever way to do this online here:
http://forums.devshed.com/c-programming-42/printing-a-float-as-a-hex-number-567826.html
And here's my implementation of their advice in C++
fileout << hex << *(int*)&a[i] << endl;
fileout << hex << *(int*)&b[i] << endl;
fileout << hex << *(int*)&c[i] << endl;
This works for most of the cases. However, some of the cases, the strings are not 8 characters wide. Sometimes they are only one bit long. Here is the sample of the output:
af1fe786
ffbbff0b
fffbff0b
7fbcbf00 <-I like it, but has zeros at the end
77fefe77
7ffcbf00
fdad974d
f2fc7fef
4a2fff56
67de7744
fdf7711b
a9662905
cd7adf0 <-- problem
5f79ffc0
0 <--- problem
6ebbc784
cffffb83
de3bcacf
e7b3de77
ec7f660b
3ab44ae4
aefdef82
fffa9fd6
fd1ff7d2
62f4 <--why not "62f40000"
ebbf0fa6
ddd78b8d
4d62ebb3
ff5bbceb
3dfc3f61
ff800000 <- zeros at end, but still 8 bytes?
df35b371
e0ff7bf1
3db6115d
fbbfbccc
ddf69e06
5d470843
a3bdae71
fe3fff66
0 <--problem
979e5ba1
febbe3b9
0 <-problem
fdf73a80
efcf77a7
4d9887fd
cafdfb07
bf7f3f35
4afebadd
bffdee35
efb79f7f
fb1028c <--problem
I want 8-character representations. As for the case of zero, I want to convert it to "00000000".
But I am really confused about the ones that are only 4, 5, 6, 7 characters long. Why do some numbers get zero filled at the end and others get truncated? If an int is 32 bits, why does sometimes only one bit show up? Is this due infamous "subnormal" numbers?
Thanks.
See Question&Answers more detail:os