Skip to content

Instantly share code, notes, and snippets.

@aunyks
Last active October 10, 2018 00:09
Show Gist options
  • Save aunyks/aaf49dfef210888ca2c3c9ef73785334 to your computer and use it in GitHub Desktop.
Save aunyks/aaf49dfef210888ca2c3c9ef73785334 to your computer and use it in GitHub Desktop.
def to_bin(n):
return bin(n)[2:] if n >= 0 else bin(n)[3:]
def to_int(b):
return int(b, 2)
def ones_complement(b):
return b.replace('1', '2').replace('0', '1').replace('2', '0')
def twos_complement(b):
return to_bin(to_int(ones_complement(b)) + 1)
def sign_mag(n, num_bits=1):
binary = to_bin(n)
num_zeroes = (num_bits - len(binary)) - 1
return '1' + ('0' * num_zeroes) + binary if n < 0 else '0' + ('0' * num_zeroes) + binary
def to_excess_m(n, m):
return to_bin(n + m)
def from_excess_m(b, m):
return to_int(b) - m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment