2 \chapter[Encoding/Decoding (Informative)]{Variable Length Data: Encoding/Decoding (Informative)}
3 \label{app:variablelengthdataencodingdecodinginformative}
4 \addtoindexx{LEB128 encoding!algorithms}
6 Here are algorithms expressed in a C-like pseudo-code to
7 encode and decode signed and unsigned numbers in LEB128
14 byte = low order 7 bits of value;
16 if (value != 0) /* more bytes to come */
17 set high order bit of byte;
21 \caption{Algorithm to encode an unsigned integer}
22 \addtoindexx{LEB128!unsigned, encoding as}
28 negative = (value < 0);
29 size = no. of bits in signed integer;
32 byte = low order 7 bits of value;
34 /* the following is unnecessary if the
35 * implementation of >>= uses an arithmetic rather
36 * than logical shift for a signed left operand
40 value |= - (1 <<(size - 7));
41 /* sign bit of byte is second high order bit (0x40) */
42 if ((value == 0 && sign bit of byte is clear) ||
43 (value == -1 && sign bit of byte is set))
46 set high order bit of byte;
50 \caption{Algorithm to encode a signed integer}
51 \addtoindexx{LEB128!signed, encoding as}
60 byte = next byte in input;
61 result |= (low order 7 bits of byte << shift);
62 if (high order bit of byte == 0)
67 \caption{Algorithm to decode an unsigned LEB128 integer}
68 \addtoindexx{LEB128!unsigned, decoding of}
75 size = number of bits in signed integer;
78 byte = next byte in input;
79 result |= (low order 7 bits of byte << shift);
81 /* sign bit of byte is second high order bit (0x40) */
82 if (high order bit of byte == 0)
85 if ((shift <size) && (sign bit of byte is set))
87 result |= - (1 << shift);
89 \caption{Algorithm to decode a signed LEB128 integer}
90 \addtoindexx{LEB128!signed, decoding of}