Skip to content

Instantly share code, notes, and snippets.

@brake
Created April 3, 2015 08:18
Show Gist options
  • Save brake/fab91a65ce2b396c84ad to your computer and use it in GitHub Desktop.
Save brake/fab91a65ce2b396c84ad to your computer and use it in GitHub Desktop.
Swap between list of bytes and integer value
def bytes2int(b):
"""Convert list/tuple of two bytes to integer value"""
if len(b) != 2: raise ValueError('b must have exactly 2 items')
return (b[0] << 8) + b[1]
def int2bytes(i):
"""Convert integer value to list of bytes"""
if i > 0xFFFF:
raise ValueError()
return [i >> 8, i & 0x00FF]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment