Search code examples
webassembly

Integer Literals in WebAssembly Binary


I am using this demo to understand how WebAssembly text format is compiled into binary.

One thing I don't understand is the integer literals used in i32.const and i64.const.

For instance, the code for i32.const -1 is as follows:

0000024: 41                                        ; i32.const
0000025: 7f                                        ; i32 literal

How exactly does 0x7f (127 in decimal) relate to -1?

Here is the code for i32.const 1234:

0000024: 41                                        ; i32.const
0000025: d209                                      ; i32 literal

I know that WASM is little-endian, so the first byte in the WASM hexadecimal representation (d2) corresponds to the last byte in normal binary notation. The binary representation of 1234 in 32 bits is 00000000 00000000 00000100 11010010. The last byte is 210, which is d2 in hexadecimal. That matches what I see in the WASM code. But the byte before that is 4. Where does 09 come from in the WASM code?

There are many other examples that don't make sense to me. Where are these integer literals coming from?


Solution

  • 0x7f is the two's complement representation of -1.

    0x31 is the opcode for i32.const.

    d209 (0x09d2) is the Unsigned LEB128 of 1234 (0x04d2)

    Unsigned LEB128