番号は、各バイトが番号の各バイトをこの順序で表す文字列に直接変更する必要があります。
たとえば、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関数はありますか?
あなたが行う「デコード」は非常に脆弱なので、もう少し厳密なものがあります。
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加