Kit
Variables

getShortU16Codec

const getShortU16Codec: () => VariableSizeCodec<bigint | number, number>

Returns a codec for encoding and decoding shortU16 values.

It serializes unsigned integers using 1 to 3 bytes based on the encoded value. The larger the value, the more bytes it uses.

  • If the value is <= 0x7f (127), it is stored in a single byte and the first bit is set to 0 to indicate the end of the value.
  • Otherwise, the first bit is set to 1 to indicate that the value continues in the next byte, which follows the same pattern.
  • This process repeats until the value is fully encoded in up to 3 bytes. The third and last byte, if needed, uses all 8 bits to store the remaining value.

In other words, the encoding scheme follows this structure:

0XXXXXXX                   <- Values 0 to 127 (1 byte)
1XXXXXXX 0XXXXXXX          <- Values 128 to 16,383 (2 bytes)
1XXXXXXX 1XXXXXXX XXXXXXXX <- Values 16,384 to 4,194,303 (3 bytes)

Returns

VariableSizeCodec<bigint | number, number>

A VariableSizeCodec<number | bigint, number> for encoding and decoding shortU16 values.

Example

Encoding and decoding shortU16 values.

const codec = getShortU16Codec();
const bytes1 = codec.encode(42);    // 0x2a
const bytes2 = codec.encode(128);   // 0x8001
const bytes3 = codec.encode(16384); // 0x808001
 
codec.decode(bytes1); // 42
codec.decode(bytes2); // 128
codec.decode(bytes3); // 16384

Remarks

This codec efficiently stores small numbers, making it useful for transactions and compact representations.

If you need a fixed-size u16 codec, consider using getU16Codec.

Separate getShortU16Encoder and getShortU16Decoder functions are available.

const bytes = getShortU16Encoder().encode(42);
const value = getShortU16Decoder().decode(bytes);

See

On this page