I'm trying to make a binary2acii and vise versa Dictonary
via Python shell. I'm a bit stuck:
Dictonary
I'm new to this.
binary2ascii = {},
format (127,"08b")
for i in range(0,127): chr(i)
It sounds like you need to spend a little more time learning Python essentials.
Anyway, here's a way to make a dictionary that handles both converting a bitstring to a character and vice versa. I just loop over range(65, 70)
to keep the output small.
from pprint import pprint
binary2ascii = {}
for i in range(65, 70):
bits = format(i, "08b")
char = chr(i)
binary2ascii[bits] = char
binary2ascii[char] = bits
pprint(binary2ascii)
output
{'01000001': 'A',
'01000010': 'B',
'01000011': 'C',
'01000100': 'D',
'01000101': 'E',
'A': '01000001',
'B': '01000010',
'C': '01000011',
'D': '01000100',
'E': '01000101'}
Also, you can accomplish such 'translation' without the dictionary, like this:
def asc2binii(ch):
return bin(ord(ch))
def bin2ascii(bin_int):
return chr(int(bin_int, 2))
char_input="a"
binary_repr = asc2binii(char_input)
print(binary_repr)
ch_returned = bin2ascii(binary_repr)
print(ch_returned)
will print:
0b1100001
a
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.