fj1*_*23x 11 python string int base64 encode
我正在尝试将int编码为base64,我这样做:
foo = 1
base64.b64encode(bytes(foo))
Run Code Online (Sandbox Code Playgroud)
预期产量: 'MQ=='
给定输出: b'AA=='
我做错了什么?
编辑:在Python 2.7.2中正常工作
小智 7
如果使用整数N初始化字节(N),它将为您提供使用空字节初始化的长度为N的字节:
>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Run Code Online (Sandbox Code Playgroud)
你想要的是字符串"1"; 所以将其编码为字节:
>>> "1".encode()
b'1'
Run Code Online (Sandbox Code Playgroud)
现在,base64会给你b'MQ==':
>>> import base64
>>> base64.b64encode("1".encode())
b'MQ=='
Run Code Online (Sandbox Code Playgroud)
尝试这个:
foo = 1
base64.b64encode(bytes([foo]))
Run Code Online (Sandbox Code Playgroud)
或者
foo = 1
base64.b64encode(bytes(str(foo), 'ascii'))
# Or, roughly equivalently:
base64.b64encode(str(foo).encode('ascii'))
Run Code Online (Sandbox Code Playgroud)
第一个示例对 1 字节整数进行编码1。第二个示例对 1 字节字符串进行编码'1'。