How do I write a long integer as binary in Python?

后端 未结 9 1388
梦谈多话
梦谈多话 2021-01-12 06:20

In Python, long integers have unlimited precision. I would like to write a 16 byte (128 bit) integer to a file. struct from the standard library supports only u

9条回答
  •  情书的邮戳
    2021-01-12 06:42

    I think for unsigned integers (and ignoring endianness) something like

    import binascii
    
    def binify(x):
        h = hex(x)[2:].rstrip('L')
        return binascii.unhexlify('0'*(32-len(h))+h)
    
    >>> for i in 0, 1, 2**128-1:
    ...     print i, repr(binify(i))
    ... 
    0 '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    1 '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'
    340282366920938463463374607431768211455 '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
    

    might technically satisfy the requirements of having non-Python-specific output, not using an explicit mask, and (I assume) not using any non-standard modules. Not particularly elegant, though.

提交回复
热议问题