-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_conversion.py
40 lines (30 loc) · 964 Bytes
/
data_conversion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Convert text to a string of 1s and 0s (bit string)
def text_to_bits(text):
bits = ""
for t in text:
bits += format(ord(t), '07b')
return bits
# Convert string of binary back to ascii
def bits_to_text(bits):
text = ""
start = 0
end = 7
# Loop through the bits and convert sections to ascii value
while end <= len(bits):
bits_segment = bits[start:end]
text += chr(int(bits_segment, 2))
start += 7
end += 7
return text
# Zero pad the data to a size that is a multiple of the modulus
def pad_bits(bits, modulus, end=True):
leftover_bits = len(bits) % modulus
# If there are leftover bits, pad the end
if leftover_bits != 0:
padding = modulus - leftover_bits
# Add the zeroes to either the front or the rear
if end:
bits = bits + "0"*(padding)
else:
bits = "0"*(padding) + bits
return bits