-1

该数字应直接更改为字符串,其中每个字节按该顺序表示数字中的每个字节。

例如,303856920984473976136907479138614277609 应该变成 '\xe4\x98\xb6\xdb\xed~\x1c\xd2X\xa5\xd1\xa9\xdaNu\xe9'

>>>hex(303856920984473976136907479138614277609)
'0xe498b6dbed7e1cd258a5d1a9da4e75e9L'
>>>>>> 'e498b6dbed7e1cd258a5d1a9da4e75e9'.decode('hex')
'\xe4\x98\xb6\xdb\xed~\x1c\xd2X\xa5\xd1\xa9\xdaNu\xe9'

是否有 python 函数可以直接执行此操作?

4

2 回答 2

2

您所做的“解码”非常脆弱,所以这里有一些更严格的东西:

import struct
from functools import partial
from itertools import imap

def to_bytes(number):
    # This can only pack an unsigned long long
    # so we need to split the number into those
    packer = partial(struct.pack, ">Q")

    # How many unsigned long longs needed to hold the number
    iterations = (number.bit_length() // 64) + 1

    # Get the parts
    sections = ((number >> i*64) & 0xFFFFFFFFFFFFFFFF for i in reversed(xrange(iterations)))

    # And map "packer" over them
    return b"".join(imap(packer, sections)).lstrip("\x00")

它不是真正的“内置”,但它不会因为很多数字而中断:

>>> to_bytes(0x12300FFABACAADABAF0)
'\x01#\x00\xff\xab\xac\xaa\xda\xba\xf0'

>>> hex(0x12300FFABACAADABAF0)[2:].decode('hex')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found

并且它可以说比通过hex,条纹尾随和前面的非数字字符,如果需要,用零填充然后转码更干净。

在 Python 3 中,这要容易得多:

>>> number.to_bytes(number.bit_length()//8+1, "big")
b'\x01#\x00\xff\xab\xac\xaa\xda\xba\xf0'

%~> python2
Python 2.7.5 (default, May 12 2013, 12:00:47) 
[GCC 4.8.0 20130502 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> (324).bit_length()
9
于 2013-09-22T12:24:03.703 回答
1

我认为没有标准功能可以做到这一点,您可以轻松定义一个:

def to_bytes(number):
    return ("%x" % number).decode('hex') 
于 2013-09-22T03:59:34.337 回答