在 Python 3 中将整数的字符串表示编码为 base64

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18616657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:14:27  来源:igfitidea点击:

Encode string representation of integer to base64 in Python 3

pythonstringintbase64encode

提问by fj123x

I'm trying to encode an int in to base64, i'm doing that:

我正在尝试将 int 编码为 base64,我正在这样做:

foo = 1
base64.b64encode(bytes(foo))

expected output:'MQ=='

预期输出:'MQ=='

given output:b'AA=='

给定输出:b'AA=='

what i'm doing wrong?

我做错了什么?

Edit: in Python 2.7.2 works correctly

编辑:在 Python 2.7.2 中正常工作

采纳答案by Rob?

Try this:

尝试这个:

foo = 1
base64.b64encode(bytes([foo]))

or

或者

foo = 1
base64.b64encode(bytes(str(foo), 'ascii'))
# Or, roughly equivalently:
base64.b64encode(str(foo).encode('ascii'))

The first example encodes the 1-byte integer 1. The 2nd example encodes the 1-byte character string '1'.

第一个示例对 1 字节整数进行编码1。第二个示例对 1 字节字符串进行编码'1'

回答by doep

If you initialize bytes(N) with an integer N, it will give you bytes of length N initialized with null bytes:

如果用整数 N 初始化 bytes(N) ,它将为您提供用空字节初始化的长度为 N 的字节:

>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

what you want is the string "1"; so encode it to bytes with:

你想要的是字符串“1”;所以将其编码为字节:

>>> "1".encode()
b'1'

now, base64 will give you b'MQ==':

现在,base64 会给你b'MQ=='

>>> import base64
>>> base64.b64encode("1".encode())
b'MQ=='