Python:如何从二进制转换为 base 64 并返回?

2022-11-26Python开发问题
105

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10