I am using the following code to print out a "binary representation" of a floating point number:
template<class F>
void printBinary(F value)
{
std::cout <<
std::bitset<sizeof(F) * 8>(*reinterpret_cast<unsigned long*>(&value)).to_string()
<< std::endl;
}
int main()
{
float f = 1;
printBinary(f);
f = 2;
printBinary(f);
f = 3;
printBinary(f);
f = 4;
printBinary(f);
f = 16;
printBinary(f);
f = 0.2;
printBinary(f);
}
It outputs:
00111111100000000000000000000000
01000000000000000000000000000000
01000000010000000000000000000000
01000000100000000000000000000000
01000001100000000000000000000000
00111110010011001100110011001101
Can someone explain what parts of the output binary numbers correspond to what parts of the float? I would expect the first one just to be 10000...
. The second makes sense. I am confused about every output after that, especially the last.
Thanks in advance.
Assuming you're referring to IEEE754 binary floating point format, a 32-bit float consists of 1 sign bit, 8 exponent bits, and 23 significand (aka fraction) bits. Here's how one of your examples 0.2
get represented, as an example:
3 2 1 0
1 09876543 21098765432109876543210
S ---E8--- ----------F23----------
Binary: 0 01111100 10011001100110011001101
Hex: 3E4C CCCD
Precision: SP
Sign: Positive
Exponent: -3 (Stored: 124, Bias: 127)
Hex-float: +0x1.99999ap-3
Value: +0.2 (NORMAL)
You can read more about the format itself on the wikipedia page: https://en.wikipedia.org/wiki/IEEE_754#Basic_and_interchange_formats and also the specifics of the single-precision format in: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.