HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Modulezigzag-0.1.0.0Haskell2010

Data.Word.Zigzag

Zigzag encoding maps signed integers to unsigned integers so that numbers with a small absolute value (for instance, -1) have a small varint encoded value too. It does this in a way that "zig-zags" back and forth through the positive and negative integers, so that -1 is encoded as 1, 1 is encoded as 2, -2 is encoded as 3, and so on.

zigzag(n) = { 2 * n       if 0 <= n
            { -2 * n - 1  if n < 0

This description was adapted from https:/developers.google.comprotocol-buffersdocsencoding#signed-ints which is released under https://creativecommons.org/licenses/by/4.0/

  • 8 values
  • Packagezigzag-0.1.0.0
  • Exports8
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceZigzag.hs
valuetoZigzagNative :: Int -> Word
#

Encode a native-size integer with zigzag.

In C, this is:

(n << 1) ^ (n >> (CHAR_BIT * sizeof(int) - 1))
valuefromZigzagNative :: Word -> Int
#

Decode a native-size zigzag-encoded integer.

In C, this is:

(n >> 1) ^ (~(n & 1) + 1)
valuetoZigzag32 :: Int32 -> Word32
#

Encode a 32-bit integer with zigzag.

In C, this is:

(n << 1) ^ (n >> 31)
valuefromZigzag32 :: Word32 -> Int32
#

Decode a 32-bit zigzag-encoded integer.

In C, this is:

(n >> 1) ^ (~(n & 1) + 1)
valuetoZigzag64 :: Int64 -> Word64
#

Encode a 64-bit integer with zigzag.

In C, this is:

(n << 1) ^ (n >> 63)
valuefromZigzag64 :: Word64 -> Int64
#

Decode a 64-bit zigzag-encoded integer.

In C, this is:

(n >> 1) ^ (~(n & 1) + 1)