Elias Gamma/Delta Codes

medium · compression, universal-codes, bit-io

Elias Gamma & Delta Codes

Implement Elias gamma and delta codes for positive integers using MSB-first bit order.

Functions

func EncodeGamma(n uint64) []byte
func DecodeGamma(data []byte) (uint64, bool)

func EncodeDelta(n uint64) []byte
func DecodeDelta(data []byte) (uint64, bool)

Behavior

  • Inputs are positive integers (n >= 1).
  • Encoders return a byte slice containing a single codeword padded with trailing zeros to the next byte.
  • Decoders read exactly one codeword from data and ignore any trailing zero padding.
  • Return ok=false if the codeword is invalid, incomplete, or represents a value outside uint64. Gamma may have at most 63 leading zeros; delta's decoded bit length must be 1..64.
  • After that one codeword, all remaining bits must be zero; a trailing one is invalid. This API does not decode a concatenated sequence.

Definitions

Gamma:

  • Let L = floor(log2 n) + 1.
  • Write L-1 zeros, then the L-bit binary of n.

Delta:

  • Let L = floor(log2 n) + 1.
  • Write gamma(L), then the lower L-1 bits of n.
Run tests to see results
No issues detected
    Join Discord