Python从base64到binary的转换

xyhw6mcr  于 2023-04-08  发布在  Python
关注(0)|答案(2)|浏览(138)

我有一个关于转换base64编码字符串到二进制的问题。我在下面的链接中收集Fingerprint 2D,

url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/108770/property/Fingerprint2D/xml"

Fingerprint2D=AAADccB6OAAAAAAAAAAAAAAAAAAAAAAAAAA8WIEAAAAAAACxAAAAHgAACAAADAzBmAQwzoMABgCI AiTSSACCCAAhIAAAiAEMTMgMJibMsZuGeijn4BnI+YeQ0OMOKAACAgAKAABQAAQEABQAAAAAAAAA AA==

Pubchem中的descriptiong说这是115字节的字符串,转换成二进制时应该是920位,我试着用下面的方法将其转换成二进制,

response = requests.get(url)
    tree = ET.fromstring(response.text)

    for el in tree[0]:
        if "Fingerprint2D" in el.tag:
            fpp = bin(int(el.text, 16))
            print(len(fpp))

如果我使用上面的代码,我会得到以下错误,“值错误:base 16的int()的文字无效:
如果我使用下面的代码,fpp(二进制)的长度等于1278,这不是我所期望的。

response = requests.get(url)
    tree = ET.fromstring(response.text)

    for el in tree[0]:
        if "Fingerprint2D" in el.tag:
            fpp = bin(int(hexlify(el.text), 16))
            print(len(fpp))

非常感谢!

hm2xizp9

hm2xizp91#

要解码base64格式,需要将bytes对象传递给base64.decodebytes函数:

import base64

t = "AAADccB6OAAAAAAAAAAAAAAAAAAAAAAAAAA8WIEAAAAAAACxAAAAHgAACAAADAzBmAQwzoMABgCI AiTSSACCCAAhIAAAiAEMTMgMJibMsZuGeijn4BnI+YeQ0OMOKAACAgAKAABQAAQEABQAAAAAAAAA AA==".encode("ascii")

decoded = base64.decodebytes(t)

print(decoded)
print(len(decoded)*8)

我得到以下结果:

b'\x00\x00\x03q\xc0z8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00<X\x81\x00\x00\x00\x00\x00\x00\xb1\x00\x00\x00\x1e\x00\x00\x08\x00\x00\x0c\x0c\xc1\x98\x040\xce\x83\x00\x06\x00\x88\x02$\xd2H\x00\x82\x08\x00! \x00\x00\x88\x01\x0cL\xc8\x0c&&\xcc\xb1\x9b\x86z(\xe7\xe0\x19\xc8\xf9\x87\x90\xd0\xe3\x0e(\x00\x02\x02\x00\n\x00\x00P\x00\x04\x04\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00'
920

所以920位符合预期。
要获取二进制数据,只需迭代字节并使用format和零填充到8位数(bin添加了0b头部,因此它不适合)转换为二进制数据,然后将字符串一起join

print("".join(["{:08b}".format(x) for x in decoded]))

结果:

00000000000000000000001101110001110000000111101000111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011110001011000100000010000000000000000000000000000000000000000000000001011000100000000000000000000000000011110000000000000000000001000000000000000000000001100000011001100000110011000000001000011000011001110100000110000000000000110000000001000100000000010001001001101001001001000000000001000001000001000000000000010000100100000000000000000000010001000000000010000110001001100110010000000110000100110001001101100110010110001100110111000011001111010001010001110011111100000000110011100100011111001100001111001000011010000111000110000111000101000000000000000001000000010000000000000101000000000000000000101000000000000000001000000010000000000000101000000000000000000000000000000000000000000000000000000000000000000

(如预期的那样,为920个字符)

r8uurelv

r8uurelv2#

使用Python 3执行此操作的最简单方法是:

import base64    
base64.b64decode(base64_to_binary_input)

相关问题