Python:如何从二进制转换为base 64并转换回base? [英] Python: How do I convert from binary to base 64 and back?

查看:504
本文介绍了Python:如何从二进制转换为base 64并转换回base?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我有一些二进制值:

Lets say I have some binary value:

0b100

并希望将其转换为base64

and want to convert it to base64

执行base64.b64decode(0b100)告诉我,它期望的是字符串,而不是整数....现在,我不想使用字符串.

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并转换回base?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆