的Python:二进制文件/十六进制字符串转换?

我有一个具有二进制和字符串中的字符的字符串,我想将其转换为二进制,再为十六进制。

该字符串是如下:

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

我该如何去在Python转换这个字符串,以便以十六进制格式输出与此类似下面?

24208040901811001B12050809081223431235113245422F0A23000000000000000000001F

--------------解决方案-------------

您可以使用卡特福德和十六进制是这样的:

>>> 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

分类:蟒蛇 时间:2015-03-15 人气:0
分享到:

相关文章

Copyright (C) 55228885.com, All Rights Reserved.

55228885 版权所有 京ICP备15002868号

processed in 0.536 (s). 10 q(s)