简体   繁体   English

如何在Python 3中将二进制字符串转换为类似字节的对象?

[英]How to Convert Binary String to Byte-like Object in Python 3?

I have this line in my program: TextV = base64.b64decode('0cQ+bNsObaw=') and the value of TextV is b'\\xd1\\xc4>l\\xdb\\x0em\\xac' . 我的程序中有以下代码行: TextV = base64.b64decode('0cQ+bNsObaw=')TextV值为b'\\xd1\\xc4>l\\xdb\\x0em\\xac' Then I run this to convert TextV to binary: 然后运行此命令将TextV转换为二进制文件:

TextVBin = ''.join(format(x, 'b') for x in bytearray(TextV))

and the value of TextVBin is '11010001110001001111101101100110110111110110110110101100' . 并且TextVBin值为'11010001110001001111101101100110110111110110110110101100' Now, I wanna again convert TextVBin format to TextV format(ie b'\\xd1\\xc4>l\\xdb\\x0em\\xac' ) But I googled and I couldn't find any answer. 现在,我想再次将TextVBin格式转换为TextV格式(即b'\\xd1\\xc4>l\\xdb\\x0em\\xac' ),但是我用b'\\xd1\\xc4>l\\xdb\\x0em\\xac'搜索,但找不到任何答案。 How can I do this in Python 3? 如何在Python 3中做到这一点?

I would use: 我会用:

import struct
TextVBin = "{:b}".format(struct.unpack(">Q", TextV)[0])

to convert your TextV to binary string. 将您的TextV转换为二进制字符串。

It however produces 1101000111000100001111100110110011011011000011100110110110101100 which is different than your own output, but I guess that is because leading 0 are truncated for each byte with your own method. 但是,它会生成1101000111000100001111100110110011011011000011100110110110101100 ,这与您自己的输出不同,但是我猜这是因为使用您自己的方法会为每个字节将前导0截断。 So your method is wrong. 所以你的方法是错误的。

using struct: 1101000111000100001111100110110011011011000011100110110110101100 使用结构: 1101000111000100001111100110110011011011000011100110110110101100

using yours: 1101000111000100 111110 110110011011011 1110 110110110101100 使用您的电话: 1101000111000100 111110 110110011011011 1110 110110110101100

Then to convert this binary string back to bytes: 然后将此二进制字符串转换回字节:

int('1101000111000100001111100110110011011011000011100110110110101100', 2).to_bytes(8, 'big')

Note: I assumed that your TextVBin is 8 bytes long and big endian based on your example. 注意:根据您的示例,我假设您的TextVBin长8字节,且字节序大。 If length is variable, my answer does not apply. 如果长度可变,我的答案将不适用。

The problem is that your format string truncates leading zeros. 问题是您的格式字符串会截断前导零。 You should use 你应该用

TextVBin = ''.join('{:08b}'.format(x) for x in bytearray(TextV))

which will format each byte with exactly 8 binary digits. 它将使用精确的8个二进制数字格式化每个字节。 Then, to reverse, simply do 然后,要扭转,只需做

TextV = bytearray([int(TextVBin[i:i+8], 2) for i in range(0, len(TextVBin), 8)])

For example: 例如:

>>> import base64
>>> TextV = base64.b64decode('0cQ+bNsObaw=')
>>> TextV
b'\xd1\xc4>l\xdb\x0em\xac'
>>> TextVBin = ''.join('{:08b}'.format(x) for x in bytearray(TextV))
>>> TextVBin
'1101000111000100001111100110110011011011000011100110110110101100'
>>> TextV = bytearray([int(TextVBin[i:i+8], 2) for i in range(0, len(TextVBin), 8)])
>>> TextV
bytearray(b'\xd1\xc4>l\xdb\x0em\xac')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM