#convert a decimal number to a string def num_to_string(num): bits = num_to_bits(num) return bits_to_string(bits) def string_to_num(s): bits = string_to_bits(s) return int(bits, 2) #converts a string to a bitstream def string_to_bits(s): encoded = "" for ch in s: encoded += char_to_5bit(ch) return encoded #converts a bitstream to a string def bits_to_string(s): decoded = "" for i in range(0, len(s), 5): next_bits = s[i:i+5] ch = bits_to_char(next_bits) decoded += ch return decoded #converts a decimal number to a string of bits def num_to_bits(num): binary_string = str(format(num, 'b')) if len(binary_string) % 5 == 0: return binary_string else: num_leading_zeros = 5 - (len(binary_string)%5) return '0' * num_leading_zeros + binary_string punctuation_to_num = {'.': 27, ',': 28, '!': 29, "'": 30, "-": 31} num_to_puncutation = {27: '.', 28: ',', 29: '!', 30:"'", 31: "-"} def char_to_5bit(ch): """ Converts a single character to a 5-bit binary string. """ # Check for space first. if ch == ' ': return '00000' # Convert character to lowercase for uniform processing. ch = ch.lower() # If it's a letter, map it from a=1, b=2, ..., z=26. if 'a' <= ch <= 'z': num = ord(ch) - ord('a') + 1 # a -> 1, b -> 2, ..., z -> 26 return format(num, '05b') # map punctuation to 5-bits as in punctuation_to_num elif ch in punctuation_to_num: return format(punctuation_to_num[ch], '05b') return '' def bits_to_char(bits): if len(bits) != 5: print("length is wrong!") return '' try: num = int(bits, 2) #convert the bitstring into a decimal integer except ValueError: return '' if num == 0: #0 = space return ' ' elif 1 <= num <= 26: #letters indexed by position in alphabet return chr(num + ord('a') + -1) elif num in num_to_puncutation: #map numbers to punctuation as in num_to_punctuation return num_to_puncutation[num]