如何将数组中的一组字节从hexa转换为十进制(python)?

时间:2017-06-07 13:31:18

标签: python

我有一个文件,每行包含一组字节,例如:

4655d16c690f2789c2d3e803e388637f
16161b1504137217336d403e2a03c669
fa79c5ffe35d112915f0f3243fc68fb4
87d57d0a63e52b6df869eb5c0aac4328
640c2eefb7829d863f7aa686bc513acc
4024767c463558b7c7cd0ffd4f0aaa6d
18ee0b17f5b5206df0443e658b105990
7b40bf42d2cfc290eed4c4edcb9d3e91
b57dad9833c3e174e05a5ae75cac70ed

我想转换数组中的行,然后转换十进制的字节,例如:

4655d16c690f2789c2d3e803e388637f

结果是:

46 55 d1 6c 69 0f 27 89 c2 d3 e8 03 e3 88 63 7f

然后转换为十进制的每个字节:

 [70,85,209,108,105,15,39,137,194,211,232,3,136,227,99,127]

我尝试使用此代码,

with open(Srcpath, 'r') as f:
        with open(Destpath, 'w') as fp:
            for key in f:
                key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
                rejoined = ' '.join(key_Separated)
                Decimal= [i for i, b in enumerate(rejoined ) if b=='1']
                print(Decimal)
                fp.write(str(Decimal))

所以它给出了错误的结果:

[43]
[21, 45]
[27, 42]
[13, 31, 37, 42]
[16, 21, 28]
[13, 36]
[12, 43, 46]
[0, 6, 18, 27, 37]

我怎么能纠正他们?

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

import re

data = '''4655d16c690f2789c2d3e803e388637f
16161b1504137217336d403e2a03c669
fa79c5ffe35d112915f0f3243fc68fb4
87d57d0a63e52b6df869eb5c0aac4328
640c2eefb7829d863f7aa686bc513acc
4024767c463558b7c7cd0ffd4f0aaa6d
18ee0b17f5b5206df0443e658b105990
7b40bf42d2cfc290eed4c4edcb9d3e91
b57dad9833c3e174e05a5ae75cac70ed'''

data = [re.findall('..', item) for item in data.split('\n') if item]
result = [[int(x, 16) for x in item] for item in data]

答案 1 :(得分:0)

Python有一个内置的库,可以进行所需的转换。鉴于您的数据为data.txt

#!python3
from binascii import unhexlify
from pprint import pprint

with open('data.txt') as f:
    pprint([list(unhexlify(line.strip())) for line in f])
[[70, 85, 209, 108, 105, 15, 39, 137, 194, 211, 232, 3, 227, 136, 99, 127],
 [22, 22, 27, 21, 4, 19, 114, 23, 51, 109, 64, 62, 42, 3, 198, 105],
 [250, 121, 197, 255, 227, 93, 17, 41, 21, 240, 243, 36, 63, 198, 143, 180],
 [135, 213, 125, 10, 99, 229, 43, 109, 248, 105, 235, 92, 10, 172, 67, 40],
 [100, 12, 46, 239, 183, 130, 157, 134, 63, 122, 166, 134, 188, 81, 58, 204],
 [64, 36, 118, 124, 70, 53, 88, 183, 199, 205, 15, 253, 79, 10, 170, 109],
 [24, 238, 11, 23, 245, 181, 32, 109, 240, 68, 62, 101, 139, 16, 89, 144],
 [123, 64, 191, 66, 210, 207, 194, 144, 238, 212, 196, 237, 203, 157, 62, 145],
 [181, 125, 173, 152, 51, 195, 225, 116, 224, 90, 90, 231, 92, 172, 112, 237]]

如果使用Python 2,字节字符串不会转换为整数列表,那么还有另一个循环来进行转换:

#!python2
from binascii import unhexlify
from pprint import pprint

with open('data.txt') as f:
    pprint([[ord(b) for b in unhexlify(line.strip())] for line in f])