Python: How do I convert from binary to base 64 and back?(Python:如何从二进制转换为 base 64 并返回?)
问题描述
假设我有一些二进制值:
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 并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:如何从二进制转换为 base 64 并返回?
基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 包装空间模型 2022-01-01
