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 并返回?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
