Skip to content

Instantly share code, notes, and snippets.

@Tolsi
Created January 21, 2020 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tolsi/aed522dab5c11f33bd61cb78824c69bb to your computer and use it in GitHub Desktop.
Save Tolsi/aed522dab5c11f33bd61cb78824c69bb to your computer and use it in GitHub Desktop.
Python twos_complement useful functions without ctypes
def twos_complement(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val
def twos_complement_string(val, bits, f):
if val >= 0:
return f(twos_complement(val, bits))
else:
return f(((abs(val) ^ (2 ** bits - 1)) + 1) & (2 ** bits - 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment