Converting Between Float and Hex Representation
Learn how to convert floating-point numbers to their hexadecimal representation and back. Essential for debugging binary protocols, file formats, and memory dumps.
Decimal Value
42.0
Float32 Hex
0x42280000
Float64 Hex
0x4045000000000000
Detailed Explanation
Converting between decimal floating-point values and their hexadecimal byte representation is a common task when debugging binary data, examining memory dumps, or implementing binary protocols.
Float32 to hex — step by step for 42.0:
- Convert 42 to binary:
101010.0 - Normalize:
1.01010 x 2^5 - Sign = 0, Exponent = 5 + 127 = 132 =
10000100, Mantissa =01010000...0 - Full binary:
0 10000100 01010000000000000000000 - Group into 4-bit nibbles:
0100 0010 0010 1000 0000 0000 0000 0000 - Convert nibbles to hex:
4 2 2 8 0 0 0 0 - Result:
0x42280000
Hex to float — step by step for 0x42280000:
- Convert hex to binary:
0100 0010 0010 1000 0000 0000 0000 0000 - Extract fields: sign =
0, exponent =10000100= 132, mantissa =01010000...0 - Actual exponent = 132 - 127 = 5
- Significand = 1.01010 (binary) = 1 + 0.25 + 0.0625 = 1.3125
- Value = (-1)^0 x 1.3125 x 2^5 = 1 x 1.3125 x 32 = 42.0
Using JavaScript to convert:
// Float to hex
function floatToHex(value) {
const buf = new ArrayBuffer(4);
new DataView(buf).setFloat32(0, value);
return '0x' + new DataView(buf).getUint32(0).toString(16).padStart(8, '0');
}
// Hex to float
function hexToFloat(hex) {
const buf = new ArrayBuffer(4);
new DataView(buf).setUint32(0, parseInt(hex, 16));
return new DataView(buf).getFloat32(0);
}
// Double to hex
function doubleToHex(value) {
const buf = new ArrayBuffer(8);
new DataView(buf).setFloat64(0, value);
const hi = new DataView(buf).getUint32(0).toString(16).padStart(8, '0');
const lo = new DataView(buf).getUint32(4).toString(16).padStart(8, '0');
return '0x' + hi + lo;
}
Common hex patterns to recognize:
| Pattern | Float32 | Meaning |
|---|---|---|
0x00000000 |
+0 | All bits zero |
0x80000000 |
-0 | Only sign bit set |
0x3F800000 |
1.0 | The unit value |
0x7F800000 |
+Infinity | Max exponent, zero mantissa |
0x7FC00000 |
NaN | Max exponent, non-zero mantissa |
0x7F7FFFFF |
3.40e+38 | Largest finite float32 |
Endianness matters:
When reading floats from binary files or network packets, the byte order depends on the platform. Big-endian (network byte order) stores the most significant byte first. Little-endian (x86) stores the least significant byte first. The hex values shown here are in big-endian order.
Use Case
Float-to-hex conversion is essential for network protocol development, binary file format implementation, embedded systems debugging, reverse engineering, and verifying correct serialization of floating-point data across different platforms and languages.