Skip to content

Instantly share code, notes, and snippets.

@mdsitton
Last active January 15, 2016 23:41
Show Gist options
  • Save mdsitton/69d2331a72b748bb4c65 to your computer and use it in GitHub Desktop.
Save mdsitton/69d2331a72b748bb4c65 to your computer and use it in GitHub Desktop.
import math
def print_bin(data):
print (format(data, '08b'))
def swap_twos_comp(data, size):
return (~data & ((0x1 << size) - 1)) + 1 # apply twos complement
def py_to_unsigned(data, outputBits):
if data < 0: # check for negitive and apply signage
# make data positive, then swap positive to negitive twos complement
data = swap_twos_comp(-data, outputBits)
else:
data &= (0x1 << outputBits) - 1 # truncate to bitsize
return data
def unsigned_to_py(data):
bl = data.bit_length()
if data & (0x1 << bl-1): # signed data
data = -1*swap_twos_comp(data, bl) # convert out of twos complement
return data
def split_to_char(data, byteSize, signed=False):
if signed:
data = py_to_unsigned(data, byteSize*8)
else:
byteActual = data.bit_length()
mask = (0x1 << 8) - 1
bytesStr = bytearray()
for i in range(byteSize):
if not signed and (8*i) > byteActual:
# we dont need to worry about signed values because
# `int_to_unsigned` pads the signed values properly
# so this will only happen for unsigned ints
bytesStr.append(0x00)
else:
# Here we move the mask over by the shift value
# mask the data value, and shift it all back to get the next byte.
bytesStr.append((data >> (8*i)) & mask)
return bytesStr
def chars_to_unsigned(data, outputBits):
output = 0
for i, d in enumerate(data):
output |= d << (i*8)
return output & ((0x1 << outputBits) - 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment