【问题标题】:Has Python 3 to_bytes been back-ported to python 2.7?Python 3 to_bytes 是否已向后移植到 python 2.7?
【发布时间】:2018-01-25 07:11:22
【问题描述】:

这是我追求的功能:-

http://docs.python.org/3/library/stdtypes.html#int.to_bytes

我需要大字节序支持。

【问题讨论】:

    标签: python


    【解决方案1】:

    根据@nneonneo 的回答,这里有一个模拟 to_bytes API 的函数:

    def to_bytes(n, length, endianess='big'):
        h = '%x' % n
        s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
        return s if endianess == 'big' else s[::-1]
    

    【讨论】:

    • 不是整个 API...
    • 这在 Python 3 中似乎不起作用:AttributeError: 'str' object has no attribute 'decode',因此它不是 2/3 兼容性的可移植解决方案。
    • 对于 Python 3.4,你需要 'h = hex(n).encode('ascii')[2:]'
    • 可以用s = '{:0{}x}'.format(n, length*2).decode('hex')代替len(h)zfill
    【解决方案2】:

    为了回答您最初的问题,int 对象的 to_bytes 方法没有从 Python 3 反向移植到 Python 2.7。它被考虑但最终被拒绝。见讨论here

    【讨论】:

      【解决方案3】:

      要在 Python 2.x 中打包任意长度的 longs,可以使用以下命令:

      >>> n = 123456789012345678901234567890L
      >>> h = '%x' % n
      >>> s = ('0'*(len(h) % 2) + h).decode('hex')
      >>> s
      '\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?\n\xd2'
      

      这会以大端顺序输出数字;对于小端,反转字符串 (s[::-1])。

      【讨论】:

        【解决方案4】:

        您或许可以改用struct.pack

        >>> import struct
        >>> struct.pack('>i', 123)
        '\x00\x00\x00{'
        

        它不会像int.to_bytes 那样做任意长度,但我怀疑你需要那个。

        【讨论】:

        • 所以使用更广泛的数据类型。如果您需要超过 64 位,则需要先自己做一些工作。
        猜你喜欢
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        • 2012-06-13
        • 2016-09-07
        • 2019-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多