Skip to content

zigzagEncode

Maps a signed 64-bit integer to an unsigned one so that values near zero stay small (0, -1, 1, -2 become 0, 1, 2, 3): the “zigzag” mapping of Protocol Buffers, used before writing a signed value as a varint.

Available since v3.1.8

import { zigzagEncode } from '@helpers4/binary';
// or, from the all-in-one package (same code, one install):
import { zigzagEncode } from 'helpers4/binary';
zigzagEncode(value: bigint): bigint
ParameterTypeDescription
valuebigintA signed integer in the 64-bit range

bigint — The unsigned zigzag value

Zigzag interleaves negatives and positives, so a varint stays short for values near zero.

zigzagEncode(-1n) // => 1n
zigzagEncode(1n)  // => 2n

The most negative value maps to the largest unsigned one.

zigzagEncode(-(1n << 63n)) // => 18446744073709551615n

View source on GitHub