在 Python 中的两个十六进制值之间递增(迭代)
问题描述
我正在学习 Python(缓慢但肯定),但需要编写一个(除其他外)在两个十六进制值之间递增的程序,例如30D681 和 3227FF.我很难找到最好的方法来做到这一点.到目前为止,我在这里看到了一段代码,它将十六进制分成 30、D6 和 81,然后像这样工作-
I'm learning Python (slowly but surely) but need to write a program that (among other things) increments between two hex values e.g. 30D681 and 3227FF. I'm having trouble finding the best way to do this. So far I have seen a snippet of code on here that separates the hex into 30, D6 and 81, then works like this-
char = 30
char2 = D6
char3 = 81
def doublehex():
global char,char2,char3
for x in range(255):
char = char + 1
a = str(chr(char)).encode("hex")
for p in range(255):
char2 = char2 + 1
b = str(chr(char2)).encode("hex")
for y in range(255):
char3 = char3 + 1
b = str(chr(char2)).encode("hex")
c = a+" "+b
print "test:%s"%(c)
doublehex()
有没有更简单的方法来增加整个值,例如像
Is there a simpler way of incrementing the whole value, e.g. something like
char = 30D681
char2 = 3227FF
def doublehex():
global char,char2
for x in range(255):
char = char + 1
a = str(chr(char)).encode("hex")
for p in range(255):
char2 = char2 + 1
b = str(chr(char2)).encode("hex")
c = a+" "+b
print "test:%s"%(c)
doublehex()
为我的完全无知道歉,我确实尝试过谷歌搜索但找不到答案...
Apologies for my complete ignorance, I really have tried Googling the answer but couldn't find it...
解决方案
只需将值视为整数,并使用 xrange()
对两个值进行范围.使用 format(value, 'X')
将其显示为十六进制:
Just treat the values as integers, and use xrange()
to range over the two values. Use format(value, 'X')
to display it as hex:
start = 0x30D681 # hex literal, gives us a regular integer
end = 0x3227FF
for i in xrange(start, end + 1):
print format(i, 'X')
如果您的开始和结束值是作为十六进制字符串输入的,请先使用 int(hexvalue, 16)
将它们转换为整数:
If your start and end values were entered as hexadecimal strings, use int(hexvalue, 16)
to turn those into integers first:
start = int('30D681', 16)
end = int('3227FF', 16)
相关文章