【问题标题】:Encode string representation of integer to base64 in Python 3 [duplicate]在Python 3中将整数的字符串表示编码为base64 [重复]
【发布时间】:2013-09-08 03:02:39
【问题描述】:

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

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

预期输出: 'MQ=='

给定输出: b'AA=='

我做错了什么?

编辑:在 Python 2.7.2 中可以正常工作

【问题讨论】:

  • 嗯...您使用的是什么版本的 Python?当我执行 base64.b64encode(bytes(1)) 或 foo=1;base64.b64encode(bytes(foo)) 时,我得到'MQ=='。另外,你在哪里运行这个?
  • 当我运行你的代码时,我得到了预期的输出。您是否在其他地方重新定义了 foo ?试试 base64.b64encode(b'1')
  • 我正在使用 Python 3.3.2
  • 已确认:在 Python 3.1.2 中,它会打印出 b'AA=='。问题不是b64encode,而是bytes()。在 Python3 中,bytes(1) 返回 b'00'
  • 注意:这绝对不是重复的。下面的答案都不是正确的。见 cmets。

标签: python string int base64 encode


【解决方案1】:

如果你用整数 N 初始化字节(N),它会给你长度为 N 的字节,用空字节初始化:

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

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

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

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

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

【讨论】:

  • base64.b64encode(i.to_bytes(ceil(i.bit_length()/8),'big'))
【解决方案2】:

试试这个:

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

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

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

【讨论】:

  • 这是返回 AQ== 而不是 MQ==
  • 第二个例子返回MQ==
  • 对于其他想要编码整数但没有预期输出的人:这可行,但编码的字符串可能比需要的长得多。那是因为通过将数字转换为字符串,您只使用了输入空间的一小部分,但 b64encode 不知道这一点(例如,它不知道永远不会有字母)。我认为最好使用struct 模块来执行b64encode(pack('<Q', foo).rstrip('\x00') or '\x00').rstrip('='),这将为您提供更短的大整数编码字符串。
  • 这是实际答案:base64.b64encode(i.to_bytes(ceil(i.bit_length()/8),'big')) 不应关闭问题。
  • base64.b64encode(i.to_bytes((i.bit_length()+8)//8,'big',signed=True)) 得到正确转换的签名。和int.from_bytes(base64.b64decode(z),'big',signed=True) 解码签名(我切换到使用 +8 ... //8 而不是 ceil... 少一个库,它为您提供了符号所需的额外位)
猜你喜欢
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 2019-04-15
  • 1970-01-01
  • 2023-04-04
  • 2012-11-13
相关资源
最近更新 更多