0

I want to generate a list of the hex values of all 256 byte-combinations.

Basically, I want for example 'A' => '\x41'. I've only found modules capable of converting 'A' => '41', and this is not what I want.

How am I to solve this problem? Does anybody know an appropriate module or algorithm (as I'd like to avoid hardcoding 256 hexvalues...)?

3
  • 1
    ASCII actually only has 128 values - do you mean ASCII or "fits in 8 bits"? For that matter, do you want only printable characters? Commented Sep 14, 2011 at 19:47
  • 1
    Why would you want to put it back into a string? '\x41' is equivalent to 'A' (try it). Or do you want the string literal r'\x41'? Commented Sep 14, 2011 at 19:49
  • "I've only found modules"? Which ones? That doesn't seem sensible. Perhaps you mean functions? Commented Sep 14, 2011 at 19:51

5 Answers 5

1
>>> hex(ord('A'))
'0x41'

Is that the kind of thing you want?

Maybe something like this?

for o in range(128):
    print chr(o), hex(o)

Or maybe

import string
for c in string.printable:
    print c, hex(ord(c))
Sign up to request clarification or add additional context in comments.

Comments

1

ord('A') returns the ASCII value as an integer (65 in the case of 'A'). You can think of an integer in any base you want. hex(ord('A')) gives you a nice string ("0x41" in this case), as does print "%x" % ord('A').

Comments

1

Are you trying to print b'\x00' all the way to b'\xff'? If so then my assumption is that the best answer should contain a range of 256

for o in range(256):
    print(hex(o))

Comments

0

To get the numeric value of each ASCII upper and lower case letter as a list:

from string import ascii_letters
[ord(c) for c in ascii_letters]

Comments

0

so, you found the way of doing for one char, lets just do it for all of them in a loop or list comprehension. [(chr(x), '%x' % x) for x in range(256)]

this will create a list with (char, string with value in hex). if you want the value display in some other way you can play around with the format string like

>>> 'x%02x' % ord('\r')
'x0d'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.