【问题标题】:Converting integers to bytes将整数转换为字节
【发布时间】:2013-09-27 05:18:01
【问题描述】:

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

例如,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函数可以直接做到这一点?

【问题讨论】:

  • 'Hex' 不是编码。
  • @F3AR3DLEGEND:在 3.x 中,没有。但它存在于 2.x 中。

标签: python string binary hex


【解决方案1】:

你做的“解码”是很脆弱的,所以这里稍微严谨一点:

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

【讨论】:

  • number.bit_length() 整数没有这样的属性
  • 您使用的是哪个版本的 Python?我的帖子中添加了“证据”。如果确定没有,可以使用int(math.ceil(math.log2(number))) 模拟它。
【解决方案2】:

我不认为有一个标准函数可以做到这一点,你可以很容易地定义一个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    相关资源
    最近更新 更多