Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing (iterating) between two hex values in Python

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...

like image 814
user2188291 Avatar asked Apr 25 '13 10:04

user2188291


People also ask

How do you increment a hex number in Python?

FYI the decimal value 1 is equal to the hex value 0x01 . For example to say 15 + 1 = 16 , that is identical to 0x0f + 0x01 = 0x10 . So you can increment literally any base by adding 1.

What is hex in python?

The hex() function converts the specified number into a hexadecimal value. The returned string always starts with the prefix 0x .


1 Answers

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')

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)
like image 89
Martijn Pieters Avatar answered Oct 08 '22 09:10

Martijn Pieters