2

I think that the int, tez and nat are all serialized the same way. But what is the algorithm?

I tried running some examples through the LIGO CLI but couldn't figure out the system

$ ligo interpret -s pascaligo 'Bytes.pack(1n)'
0x050001

0001 is 1 in dec.

$ ligo interpret -s pascaligo 'Bytes.pack(1000000n)'
0x050080897a

080897a is 8.423.802 in dec.

1 Answer 1

1

The 05 prefix indicates that this serialization comes from the PACK assembly instruction, and the next byte 00 in case of integers (nat, int, and tez) indicates that the type is integer. So the numbers are represented by the bytes

  • 01 for 1n
  • 80897a for 1000000n (1 million)

Reading each byte from left to right, the 1st indicates whether more bytes are coming. The 2nd bit of the first byte indicates if the number is positive or negative, 1 indicates negative, and 0 positive.

1n:

01 0x01 = 0b00000001, 1st bit is 0, and 2nd bit is zero indicating that no more bytes are coming and that this is a positive number. The remaining six bits give the value: 0b000001 = 0x01 = 1.

1000000n: 80897a = 0x80897a = 0b10000000,0b10001001,0b01111010

The first bit in each byte indicates that this value is represented by three bytes. The 2nd bit in the 1st byte indicates that this is a positive number. The remaining bits are then 0b000000, 0b0001001, 0b1111010. Reversing the byte order (because little-endian) we get: 0b11110100001001000000 = 0xf4240 = 1000000

From the documentation we get:

A variable length sequence of bytes, encoding a Zarith number. Each byte has a running unary size bit: the most significant bit of each byte tells is this is the last byte in the sequence (0) or if there is more to read (1). The second most significant bit of the first byte is reserved for the sign (positive if zero). Size and sign bits ignored, data is then the binary representation of the absolute value of the number in little endian order.

The documentation for this can be found by running tezos-codec describe alpha.script.expr binary schema For output at the time of reading, see: gist.github.com/smondet/f5b785a6bbe6adb431fd7bca5e6df91a

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.