Path: blob/master/languages/python/algorithm_binary_representation.py
1240 views
"""1Program to do binary representation of various interesting ints.2"""345def convert_to_binary(n):6binary = []7while n:8binary.append(str(n % 2))9n /= 210binary.reverse()11return "".join(binary)121314for i in range(20, 30):15print((i, convert_to_binary(i)))1617hexa_values = ['0', '1', 'A', 'FF', 'DEADBEEF', 'CAFEBABE']1819for each in hexa_values:20dec = int(each, 16)21print((each, convert_to_binary(dec)))2223"""24Find out if the machine is storing it in the one's complement or two's25complement.261 is stored as 0000 000127-1 in 1's complement is 1111 111028-1 in 2's complement is 1111 111129"""3031import struct3233if ord(struct.pack('b', -1)[0]) == 255:34print('twos complement')35else:36print('ones complement')3738for i in range(200, 255):39print((hex(i)))4041for i in range(0, 256):42print((chr(i), i, hex(i)))4344"""45Binary Addition and Subtraction46"""47a = 2048b = 104950a_bin = convert_to_binary(a)51b_bin = convert_to_binary(b)5253if len(a_bin) > len(b_bin):54b_bin = b_bin.rjust(len(a_bin), '0')55elif len(a_bin) < len(b_bin):56a_bin = a_bin.rjust(len(b_bin), '0')575859def sum_bin(a, b):60rules = {('0', '0'): (0, 0),61('0', '1'): (1, 0),62('1', '0'): (1, 0),63('1', '1'): (0, 1)64}65carry = 066sum = 067result = ""68for x, y in zip(reversed(a), reversed(b)):69sum = rules[(x, y)][0]70if carry:71sum = rules[(str(sum), str(carry))][0]72result += str(sum)73carry = rules[(x, y)][1]7475if carry:76result += str(1)7778return result[::-1]798081def sub_bin(a, b):82ones_complement = ""83for c in b:84if c == '0':85ones_complement += '1'86elif c == '1':87ones_complement += '0'8889b = ones_complement90b = sum_bin(b, '1'.rjust(len(b), '0'))9192rules = {('0', '0'): (0, 0),93('0', '1'): (1, 0),94('1', '0'): (1, 0),95('1', '1'): (0, 1)96}9798carry = 099sum = 0100result = ""101for x, y in zip(reversed(a), reversed(b)):102sum = rules[(x, y)][0]103if carry:104sum = rules[(str(sum), str(carry))][0]105result += str(sum)106carry = rules[(x, y)][1]107# unlike addition carry should be discarded.108109return result[::-1]110111112print(('a', a, a_bin))113print(('b', b, b_bin))114115print(('a+b ', sum_bin(a_bin, b_bin)))116print(('a-b ', sub_bin(a_bin, b_bin)))117118119