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 中的两个十六进制值之间递增(迭代)


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01