Skip to content

Instantly share code, notes, and snippets.

@mnot
Created September 15, 2022 09:28
Show Gist options
  • Save mnot/7e15e2199ebe7605a76000982605bbcf to your computer and use it in GitHub Desktop.
Save mnot/7e15e2199ebe7605a76000982605bbcf to your computer and use it in GitHub Desktop.
from typing import Tuple
def decode_integer(data: bytes) -> Tuple[int, int]:
v = data[0]
prefix = v >> 6
length = 1 << prefix
v = v & 0x3F
for i in range(1, length):
v = (v << 8) + data[i]
return length, v
uint8 = 256
def encode_integer(i: int) -> bytearray:
if i <= 63:
return bytearray([i])
if i <= 16383:
return bytearray([i >> 8 | 0x40, i % uint8])
if i <= 1073741823:
return bytearray(
[i >> 24 | 0x80, (i >> 16) % uint8, (i >> 8) % uint8, i % uint8]
)
if i <= 4611686018427387903:
return bytearray(
[
(i >> 56) % uint8 | 0xC0,
(i >> 48) % uint8,
(i >> 40) % uint8,
(i >> 32) % uint8,
(i >> 24) % uint8,
(i >> 16) % uint8,
(i >> 8) % uint8,
i % uint8,
]
)
raise ValueError(f"{integer} doesn't fit into 62 bits")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment