Skip to content

Instantly share code, notes, and snippets.

@stephenmm
Last active November 29, 2018 16:28
Show Gist options
  • Save stephenmm/ba209c5cca1e6583dbf44a999d5e32aa to your computer and use it in GitHub Desktop.
Save stephenmm/ba209c5cca1e6583dbf44a999d5e32aa to your computer and use it in GitHub Desktop.
Convert a value into its signed counterpart given a particular bit width. Also shows creating simple test in python with asserts and exceptions.
def bits2signed( val, width ):
'''Convert a value into its signed counterpart given a particular bit width'''
shift=width-1
max_val=(2**width)-1
if val > max_val:
raise ValueError('The value provided (%s) is greater than the bit width can represent(2^%s=%s)'%(val,width,max_val))
sign_bit_mask=1<<shift
magn_bit_mask=(1<<shift)-1
return -(val&sign_bit_mask) | (val&magn_bit_mask)
# Test that the function works as expected
assert bits2signed(0xffd, 16) == 4093
assert bits2signed(0xfffd, 16) == -3
assert bits2signed(0xffff, 16) == -1
assert bits2signed(0x8000, 16) == -32768
assert bits2signed(0x7fff, 16) == 32767
assert bits2signed(0x1, 16) == 1
assert bits2signed(0xffcb, 16) == -53
assert bits2signed(0xffffffd,32) == 268435453
assert bits2signed(0xfffffffd,32) == -3
try:
bits2signed(0xffffd, 16) # Try to call the function with an intentional error
raise Exception # If the call was succesfull raise an Exception
except ValueError: # If the call was not succesfull:
pass # Then it did what was expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment