Mauro Bringolf

Currently geeking out as WordPress developer at WebKinder and student of computer science at ETH.

Hexadecimal floating point notation

December 27, 2017
, ,

Hexadecimals come up in a lot of places in programming and computer science. I see them as a shorthand notation for raw strings of bits. I am talking about things of this kind: 0x23FFA700. The prefix 0x is used to indicate that the number should be interpreted as hexadecimal, but does not affect its value in any other way. The actual value is encoded after the prefix using digits 0-9 and letters A-F. I am not going into how that works, but it is really no different from binary representation of integers. Try a quick Google search if you are unfamiliar with these things, but they are really just notation.

I want to learn more about WebAssembly, so I recently started contributing to the open source project xtuc/js-webassembly-interpreter1. Its an interpreter for WebAssembly code written in JavaScript. It is a fun project and there will probably be more posts about it in the future on this blog. Here is a small thing I picked up from reading test cases in the official reference interpreter2. It contains floating point number literals that looked a bit weird to me at first:

(f32.const 0x1p-1)

The first part denotes the type which is a single precision (32 bit) floating point number in this case. The second part should be its value, but what number does this string represent?

Of course, Stackoverflow had the answer for me3. The part before the p encodes the significand (mantissa) and the rest is the exponent in decimal. So this is a combination of decimal and hexadecimal notation. The exponent can be negative and is taken with base 2, effectively multiplying the significand with \( 2^{exp} \). The full specification can be found as part of the WebAssembly specification itself4. Now we can decode the example from above. The significand is 0x1 and corresponds to the decimal number \( 1 \). The exponent is -1. Therefore the value represented is \( 1 * 2^{-1} = 0.5 \) in decimal.