在 Python 中的两个十六进制值之间递增(迭代)

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)