问题描述
假设我有一些二进制值:
Lets say I have some binary value:
0b100
并希望将其转换为 base64
and want to convert it to base64
执行 base64.b64decode(0b100)
告诉我它需要一个字符串,而不是一个 int....现在,我不想使用字符串.
doing base64.b64decode(0b100)
tells me that it is expecting a string, not an int.... now, I don't want to work with strings.
那么,谁能指出我将二进制数转换为 base64 数的正确方向?谢谢!
So, could anyone point me in the right direction for converting binary numbers to base64 numbers? thanks!
=D
推荐答案
取决于你如何表示值 0b100
>>> import struct
>>> val = 0b100
>>> print struct.pack('I', val).encode('base64')
BAAAAA==
这会将您的值转换为原生字节序的 4 字节整数,并将该值编码为 base64.您需要指定数据的宽度,因为 base64 确实用于以可打印字符表示二进制数据.
This will turn your value into a 4-byte integer in native endianness, and encode that value into base64. You need to specify the width of your data as base64 is really made for representing binary data in printable characters.
您通常可以通过 struct 的函数将数据编码为一串字节,然后编码为 base64.确保在解码时使用相同的数据布局和字节序.
You can typically encode data as a string of bytes via struct's functions, and then encode into base64. Ensure you're using the same data layout and endianess when decoding.
这篇关于Python:如何从二进制转换为 base 64 并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!