Created
April 3, 2015 08:18
-
-
Save brake/fab91a65ce2b396c84ad to your computer and use it in GitHub Desktop.
Swap between list of bytes and integer value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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