views:

121

answers:

7
+2  Q: 

Python iteration

I'm trying to do a simple script in Python that will print hex values and increment value like this:

 char = 0
 char2 = 0

 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 "testing with:%s"%(c)
doublehex()

Output:

testing with:01 01
testing with:01 02
testing with:01 03
[snip]
testing with:01 fd
testing with:01 fe
testing with:01 ff

Traceback (most recent call last):
  File "test2.py", line 16, in doublehex
   b = str(chr(char2)).encode("hex")
ValueError: chr() arg not in range(256)

Actually what I'm trying to do is:

01 01
01 02
[snip]
01 ff
02 01
02 02

And so on, until ff ff. What's wrong in my script?

Also it seems I can't try:

00 01
00 02

I don't know why.

+2  A: 

You need to set char2 = 0 before

for p in range(255):

And actually, you don't need counters - char,char2

Following will work from 0 to ff

for x in range(256):
    for p in range(256):
        print chr(x).encode("hex"),chr(p).encode("hex")
S.Mark
+5  A: 
for x in xrange(256):
    for y in xrange(256):
        print '%02x %02x' % (x, y)
Paul Hankin
A: 

To print a hex value, just do something like this:

for i in range(255):
    print "%x" % i
dzen
A: 

Output first, then increment.

Ignacio Vazquez-Abrams
A: 

Why not something simple like?

for x in range(0, int("FFFF", 16)):
    print "%x" % x
Dominic Bou-Samra
+1  A: 

A one liner as well (minus the import):

import itertools
hexs = itertools.product(*([[chr(x).encode("hex") for x in range(256)]] * 2))
carl
Heh, better than mine :)
Chinmay Kanchi
A: 

If you're using python 2.6, there is a 4-line way to do what you're trying:

import itertools

char_pair_list = itertools.product(range(256),range(256))
for char_pair in char_pair_list:
    print str(chr(char_pair[0])).encode("hex"), ',' , str(chr(char_pair[1])).encode("hex")
Chinmay Kanchi