Python:如何在二进制和 Base 64 之间相互转换?
假设我有一些二进制值:
0b100
并且想要将其转换为 base64
执行 base64.b64decode(0b100)
告诉我它需要一个字符串,而不是一个 int....现在,我不'不想使用字符串。
那么,有人能指出我将二进制数转换为 Base64 数的正确方向吗?谢谢!
=D
Lets say I have some binary value:
0b100
and want to convert it to base64
doing base64.b64decode(0b100)
tells me that it is expecting a string, not an int.... now, I don't want to work with strings.
So, could anyone point me in the right direction for converting binary numbers to base64 numbers? thanks!
=D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据您表示值
0b100
的方式,这会将您的值转换为本机字节序的 4 字节整数,并将该值编码为 Base64。您需要指定数据的宽度,因为 base64 实际上是为了用可打印字符表示二进制数据而设计的。
您通常可以通过 struct 的函数将数据编码为字节字符串,然后编码为 base64。确保解码时使用相同的数据布局和字节顺序。
Depending on how you represent the value
0b100
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.
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 整数。
只需转换为字符串并对其进行 Base64 编码(为您提供一个表示“4”的 Base64 的字符串)。这种方法没有什么问题,无损且简单。
如果需要,可以使用 bin 将 int 转换为二进制字符串:
Binary literals are just normal python integers.
Just convert to a string and base64 encode it (giving you a string that is the base64 representation of '4'). There is nothing wrong with this approach, it's lossless and simple.
If you want, you can use bin to convert the int into a binary string:
你的二进制值有多大?如果它可以容纳一个字节,那么您可以使用
chr
。否则,我认为您必须通过一些指数数学从中获取各个字节,并将它们排列为大端或小端,多次调用
chr
。 (编辑:yan 对struct
模块的回答更容易:)另外,我应该注意,二进制整数语法就是这样的语法。解释器将其视为另一个整数。
How large is your binary value? If it can fit in a single byte, then you can use
chr
.Otherwise I think you'll have to get the individual bytes out of it with some exponential math and arrange them in big-endian or little-endian, calling
chr
multiple times. (Edit: yan's answer with thestruct
module is easier :)Also, I should note that the binary integer syntax is just that, syntax. The interpreter sees it as just another integer.