创建范围内的十六进制代码列表

时间:2019-05-03 04:39:26

标签: python

我正在尝试创建一个已知范围内所有十六进制代码的列表。范围的例子是。 008000至00FFFF 400000至43FFFF E40000至E7FFFF我希望使用excel或python创建一个列表。由于某些十六进制代码将带有前导零,因此我也需要保持这种格式。我想将列表另存为文本文件。任何帮助将非常感激。

2 个答案:

答案 0 :(得分:1)

尝试以下代码:

start_str = input('Start of range: ')
end_str = input('End of range: ')
filename = input('Output filename: ')

start = int(start_str, 16)
end = int(end_str, 16)

with open(filename, 'w') as f:
    for i in range(start, end+1):
        f.write('{:06X}\n'.format(i))

输出

Start of range: 008000
End of range: 0080FF
Output filename: out.txt

out.txt然后包含十六进制代码


根据OP的要求,以下是一个版本,该版本还将代码附加到每个输出行:

start_str = input('Start of range: ')
end_str = input('End of range: ')
filename = input('Output filename: ')
ccode = input('Code name: ')

start = int(start_str, 16)
end = int(end_str, 16)

with open(filename, 'w') as f:
    for i in range(start, end+1):
        f.write('{:06X}, {}\n'.format(i, ccode))

输出

Start of range: 08
End of range: 0F
Output filename: out.txt
Code name: the CODE

out.txt

000008, the CODE
000009, the CODE
00000A, the CODE
00000B, the CODE
00000C, the CODE
00000D, the CODE
00000E, the CODE
00000F, the CODE

答案 1 :(得分:0)

只需将startend转换为整数,然后使用列表推导来列出十六进制字符串。

def hex_range(start, end):
    # start and end are specified as strings, e.g. '0088FF' or '0x0088FF'
    return ['{:06X}'.format(i) for i in range(int(start, 16), int(end, 16))]

(就像@metatoaster的注释所暗示的那样,06X格式字符串的意思是“宽度为6个字符,用零而不是空格来填充空白,并用十六进制而不是十进制来填充。” Here's the documentation on str.format(), if you need it


要将其保存到文本文件中,您可以执行以下操作:

# assuming you've already read in start and end
hexes = hex_range(start, end)
with open('output.txt', 'w') as outfile:  # open a file to write to
    outfile.writelines(hexes)  # write each element of hexes as a separate line in the file