简体   繁体   English

Python:使用base64解码bin

[英]Python: decode bin using base64

如果我有二进制字符串,可以说str = "010100011010101001001101100101100110101" ,它是由其他字符串的base64版本编码的,如何解码该字符串?

It would have been great if your example string is actually something meaningful rather than something made up which makes this question rather unclear, but I will try my best here to figure out what you might have meant in the most verbose manner possible. 如果您的示例字符串实际上是有意义的东西,而不是使问题变得不清楚的复杂东西,那就太好了,但是在这里,我将尽我最大的努力找出您可能以最冗长的方式讲的意思。

Assuming your actual input is a str that looks like this: 假设您的实际输入是一个如下所示的str

s = '101100101010011010000100011000001011010010110000100111000110000'

You can get the hexadecimal form of this by casting it to int using the base keyword argument 您可以使用base关键字参数将其强制转换为int以获得十六进制形式

>>> i = int(s, base=2)  # 6436561067884170800

Then turn it back into a string by formatting it like so: 然后将其格式化为如下所示,将其转换为字符串:

>>> h = '%x' % i  # '595342305a584e30'

Then use the binascii.a2b_hex function on the hexadecimal string to get the raw bytes: 然后对十六进制字符串使用binascii.a2b_hex函数来获取原始字节:

>>> b64 = binascii.a2b_hex(h)  # b'YSB0ZXN0'

If it is some valid base 64 encoded stream of bytes, you may then use base64.b64decode on that to get the actual bytes 如果它是一些有效的base 64编码字节流,则可以在其上使用base64.b64decode来获取实际字节

>>> r = base64.b64decode(b64)  # b'a test'

To turn that into a string, apply the correct codec to it (ie use bytes.encode ). 要将其转换为字符串,请对其应用正确的编解码器(即,使用bytes.encode )。

Finally, if you cared to know how I generated that input, this is all the above, reversed into a single one-line function: 最后,如果您想知道我是如何生成该输入的,则上述全部操作都可以转换为一个单行函数:

>>> '{0:b}'.format(int(binascii.b2a_hex(base64.b64encode(b'a test')), base=16))
'101100101010011010000100011000001011010010110000100111000110000'

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

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