Skip to content

Primitive Values

There are a few primitives to choose from:

Schema JavaScript value Size Encoded as
bin.bool boolean 1 byte 1 if true, 0 if false
bin.i8 number 1 byte 8-bit signed integer
bin.u8 number 1 byte 8-bit unsigned integer
bin.i16 number 2 bytes 16-bit signed integer
bin.u16 number 2 bytes 16-bit unsigned integer
bin.i32 number 4 bytes 32-bit signed integer
bin.u32 number 4 bytes 32-bit unsigned integer
bin.i64 bigint 8 bytes 64-bit signed integer
bin.u64 bigint 8 bytes 64-bit unsigned integer
bin.f16 number 2 bytes 16-bit (half precision) floating-point number
bin.f32 number 4 bytes 32-bit floating-point number
bin.string string variable UTF-8 characters, followed by a \0 character

Multi-byte values are encoded in the endianness of the bin.cursor() they are written to or read from, which defaults to the endianness of the system.

Integers outside of the range of a schema wrap around, e.g. writing 2n ** 63n with bin.i64 reads back as -(2n ** 63n), and writing -1n with bin.u64 reads back as 2n ** 64n - 1n. The 64-bit schemas take bigint values, as a number can’t represent every 64-bit integer exactly.

import * as bin from 'typed-binary';
const buffer = new ArrayBuffer(16);
// Writing four bytes into the buffer
const writer = bin.cursor(buffer);
bin.u8.write(writer, 'W'.charCodeAt(0));
bin.u8.write(writer, 'o'.charCodeAt(0));
bin.u8.write(writer, 'w'.charCodeAt(0));
bin.u8.write(writer, 0);
const reader = bin.cursor(buffer);
console.log(bin.string.read(reader)); // > Wow

When a value can only be one of a few known strings, an enum schema encodes it in fewer bytes than bin.string would.

const Direction = bin.orderedEnum('north', 'east', 'south', 'west');
type Direction = bin.ExtractOut<typeof Direction>; // 'north' | 'east' | 'south' | 'west'

There are two kinds of enums, differing in how they encode values:

  • bin.orderedEnum(...values) encodes the index of the value in a single byte, so it can have at most 256 values. Changing the order of values changes the encoding, so new values should be appended at the end.
  • bin.prefixEnum(...values) encodes the ASCII characters of the value, without a terminating character. It’s independent of the order of values, but no value can be a prefix of another (e.g. 'a' and 'ab'), and values can only contain ASCII characters.