将整数转换为字节

时间:2013-09-22 03:54:28

标签: python string binary hex

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

例如,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函数?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我认为没有标准功能,你可以轻松定义一个:

def to_bytes(number):
    return ("%x" % number).decode('hex')