Incrementing (iterating) between two hex values in Python(在 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)
这篇关于在 Python 中的两个十六进制值之间递增(迭代)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中的两个十六进制值之间递增(迭代)


- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01