Created
January 21, 2020 12:05
-
-
Save Tolsi/aed522dab5c11f33bd61cb78824c69bb to your computer and use it in GitHub Desktop.
Python twos_complement useful functions without ctypes
This file contains 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 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