簡體   English   中英

Python:二進制/十六進制字符串轉換?

[英]Python: binary/hex string conversion?

我有一個既包含二進制字符又包含字符串字符的字符串,我想先將其轉換為二進制,然后轉換為十六進制。

字符串如下:

<81>^Q<81>"^Q^@^[)^G ^Q^A^S^A^V^@<83>^Cd<80><99>}^@N^@^@^A^@^@^@^@^@^@^@j

如何在Python中轉換此字符串,以便十六進制格式的輸出與此類似?

24208040901811001B12050809081223431235113245422F0A23000000000000000000001F

您可以像這樣使用ord和hex:

>>> s = 'some string'
>>> hex_chars = map(hex,map(ord,s))
>>> print hex_chars
['0x73', '0x6f', '0x6d', '0x65', '0x20', '0x73', '0x74', '0x72', '0x69', '0x6e', '0x67']
>>> hex_string = "".join(c[2:4] for c in hex_chars)
>>> print hex_string
736f6d6520737472696e67
>>>

或使用內置編碼:

>>> s = 'some string'
>>> print s.encode('hex_codec')
736f6d6520737472696e67
>>>
>>> import binascii

>>> s = '2F'

>>> hex_str = binascii.b2a_hex(s)

>>> hex_str

>>> '3246'

要么

>>>import binascii

>>> hex_str = binascii.hexlify(s)

>>> hex_str
>>> '3246'
>>>

更快的解決方案,請參閱:

from timeit import Timer

import os
import binascii

def testSpeed(statement, setup = 'pass'):
  print '%s' % statement
  print '%s' % Timer(statement, setup).timeit()

setup = """
import os

value = os.urandom(32)
"""

# winner
statement = """
import binascii

binascii.hexlify(value)
"""

testSpeed(statement, setup)

# loser
statement = """
import binascii

value.encode('hex_codec')
"""

testSpeed(statement, setup)

結果:

import binascii

binascii.hexlify(value)

2.18547999816

value.encode('hex_codec')

2.91231595077

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM