text = 'ABC '
for x in text:
print(format(ord(x), '08b'), end='')
会给出二进制(数字)字符串:01000001010000100100001100100000
其十进制为:1094861600
第三行的意思是将二进制数(字节)序列化并显示相应的ASCII字符(对于每个8位序列),例如0x41将被替换为'A'(作为输出)。 (这里的假设是每个数字都将映射到可打印的ASCII即文本字符,并且给定的二进制数具有8位数字的倍数)。
例如,要反转(将二进制数转换为文本):
binary = "01000001010000100100001100100001"
#number of characters in text
num = len(binary)/8
for x in range(int(num)):
start = x*8
end = (x+1)*8
print (chr(int(str(binary[start:end]),2)), end='')
print()
将会输出文本:ABC!
对于一个1MB的文本文件,您可以将文本字符串分割成您的机器可以处理的块,如32位(在转换之前)
已在Python IDE中进行了测试
请参阅https://docs.python.org/3/library/codecs.html#standard-encodings以获取标准字符串编码列表,因为转换取决于编码。
这些函数将帮助在字节/整数和字符串之间进行转换,默认为UTF-8。
提供的示例使用UTF-8中的Hangul字符“한”。
def bytes_to_string(byte_or_int_value, encoding='utf-8') -> str:
if isinstance(byte_or_int_value, bytes):
return byte_or_int_value.decode(encoding)
if isinstance(byte_or_int_value, int):
return chr(byte_or_int_value).encode(encoding).decode(encoding)
else:
raise ValueError('Error: Input must be a bytes or int type')
def string_to_bytes(string_value, encoding='utf-8') -> bytes:
if isinstance(string_value, str):
return bytes(string_value.encode(encoding))
else:
raise ValueError('Error: Input must be a string type')
int_value = 54620
bytes_value = b'\xED\x95\x9C'
string_value = '한'
assert bytes_to_string(int_value) == string_value
assert bytes_to_string(bytes_value) == string_value
assert string_to_bytes(string_value) == bytes_value