python我怎么把数组里面的每个字符串转换成16进制数啊

Python027

python我怎么把数组里面的每个字符串转换成16进制数啊,第1张

先把字符串转化为数字格式,

再用hex()把十进度数字转化为十六进制数

代码如下:

source = ['1','2','3','4']

destination = []

for item in source:

    destination.append(hex(int(item)))

print(destination)

输出如下:

['0x1', '0x2', '0x3', '0x4']

这个转了十进制又转了十六进制,都是string,而不是数值

print出来,是以string 输出的。

分享一个我以前的

#比如hex.log 里面是E3F2A1

#就要往文件out.bin里写 0xE3 0xF2 0xA1

import string

HEX_file_name = "hex.log"

BIN_file_name = "out.bin"

input_file = open(HEX_file_name,'r')

output_file = open(BIN_file_name,'wb')

for lines in input_file.readlines():

lines = lines.replace(' ','').replace('\n','').upper()

for i in range(0, len(lines), 2):

chars = lines[i:i+2]

output_file.write(chr(int(chars, 16)))

input_file.close()

output_file.close()

核心就是

for i in range(0, len(lines), 2):

chars = lines[i:i+2]

output_file.write(chr(int(chars, 16)))

看懂了就懂了

out.bin可以用ultraedit或者notepad++十六进制查看