cl-tools/src/bitutils.py

78 lines
1.5 KiB
Python
Raw Normal View History

2023-04-03 23:26:59 +03:00
def align_binary_to_right(value, size):
if "b" in value:
result = value.split("b")[1]
else:
result = str(value)
return result[-size:].rjust(size, "0")
ar = align_binary_to_right
def align_binary_to_left(value, size):
if "b" in value:
result = value.split("b")[1]
else:
result = str(value)
return result[-size:].ljust(size, "0")
al = align_binary_to_left
2023-04-03 23:26:59 +03:00
def shift_left(rg, fill_bit = 0):
return rg[1:] + str(fill_bit)
2023-04-03 23:26:59 +03:00
l = shift_left
def shift_right(rg, fill_bit = 0):
return str(fill_bit) + rg[:-1]
2023-04-03 23:26:59 +03:00
r = shift_right
def sum_supplementary_codes(x, y, size):
return al(bin(int("0b"+x, 2) + int("0b"+y, 2))[2:], size)
sum = sum_supplementary_codes
def sum_supplementary_codes_right_align(x, y, size):
return ar(bin(int("0b"+x, 2) + int("0b"+y, 2))[2:], size)
rsum = sum_supplementary_codes_right_align
def sum_supplementary_codes_with_overflow(x, y, size):
result = bin(int("0b"+x, 2) + int("0b"+y, 2))[2:]
if len(result) > size:
return al(result, size), '1'
else:
return al(result, size), '0'
sump = sum_supplementary_codes_with_overflow
2023-04-03 23:26:59 +03:00
def invert_bit(b):
if b == '0':
return '1'
elif b == '1':
return '0'
else:
print(f"binutils: detected impossible call: inv({b})")
exit(1)
inv = invert_bit
def xor(x, y):
if len(x) == len(y):
result = ''
for i in zip(x, y):
if x != y:
result += '1'
else:
result += '0'
return result