Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/algorithm_binary_representation.py
1240 views
1
"""
2
Program to do binary representation of various interesting ints.
3
"""
4
5
6
def convert_to_binary(n):
7
binary = []
8
while n:
9
binary.append(str(n % 2))
10
n /= 2
11
binary.reverse()
12
return "".join(binary)
13
14
15
for i in range(20, 30):
16
print((i, convert_to_binary(i)))
17
18
hexa_values = ['0', '1', 'A', 'FF', 'DEADBEEF', 'CAFEBABE']
19
20
for each in hexa_values:
21
dec = int(each, 16)
22
print((each, convert_to_binary(dec)))
23
24
"""
25
Find out if the machine is storing it in the one's complement or two's
26
complement.
27
1 is stored as 0000 0001
28
-1 in 1's complement is 1111 1110
29
-1 in 2's complement is 1111 1111
30
"""
31
32
import struct
33
34
if ord(struct.pack('b', -1)[0]) == 255:
35
print('twos complement')
36
else:
37
print('ones complement')
38
39
for i in range(200, 255):
40
print((hex(i)))
41
42
for i in range(0, 256):
43
print((chr(i), i, hex(i)))
44
45
"""
46
Binary Addition and Subtraction
47
"""
48
a = 20
49
b = 10
50
51
a_bin = convert_to_binary(a)
52
b_bin = convert_to_binary(b)
53
54
if len(a_bin) > len(b_bin):
55
b_bin = b_bin.rjust(len(a_bin), '0')
56
elif len(a_bin) < len(b_bin):
57
a_bin = a_bin.rjust(len(b_bin), '0')
58
59
60
def sum_bin(a, b):
61
rules = {('0', '0'): (0, 0),
62
('0', '1'): (1, 0),
63
('1', '0'): (1, 0),
64
('1', '1'): (0, 1)
65
}
66
carry = 0
67
sum = 0
68
result = ""
69
for x, y in zip(reversed(a), reversed(b)):
70
sum = rules[(x, y)][0]
71
if carry:
72
sum = rules[(str(sum), str(carry))][0]
73
result += str(sum)
74
carry = rules[(x, y)][1]
75
76
if carry:
77
result += str(1)
78
79
return result[::-1]
80
81
82
def sub_bin(a, b):
83
ones_complement = ""
84
for c in b:
85
if c == '0':
86
ones_complement += '1'
87
elif c == '1':
88
ones_complement += '0'
89
90
b = ones_complement
91
b = sum_bin(b, '1'.rjust(len(b), '0'))
92
93
rules = {('0', '0'): (0, 0),
94
('0', '1'): (1, 0),
95
('1', '0'): (1, 0),
96
('1', '1'): (0, 1)
97
}
98
99
carry = 0
100
sum = 0
101
result = ""
102
for x, y in zip(reversed(a), reversed(b)):
103
sum = rules[(x, y)][0]
104
if carry:
105
sum = rules[(str(sum), str(carry))][0]
106
result += str(sum)
107
carry = rules[(x, y)][1]
108
# unlike addition carry should be discarded.
109
110
return result[::-1]
111
112
113
print(('a', a, a_bin))
114
print(('b', b, b_bin))
115
116
print(('a+b ', sum_bin(a_bin, b_bin)))
117
print(('a-b ', sub_bin(a_bin, b_bin)))
118
119