[Tutor] Conversion of each number of an integer to hex

Jeff Shannon jeff at ccvcorp.com
Wed Sep 17 15:38:26 EDT 2003


Vicki Stanfield wrote:
> I am in a situation where I have to take some number like 24 and send it
> as hex 32 (the 2) and hex 34 (the 4). Is there some builtin function to do
> this? If not, is there a commonly used method? To be clear, I have to take
> the number and break it apart into elements which I then have to convert
> to hex to send as input to another module.

What you need to do is convert the number to a string with something 
like 'x = str(24)'.  Now, if necessary, you can loop through that 
string and do something with each character.

for char in str(24):
     print hex(ord(char))

In this example, ord() converts the character to its (integer) ascii 
code, and hex() converts that integer to a hex-digit string.

However, you may not actually need to do that!  If you're trying to 
feed ascii codes to another module, odds are that if you just pass in 
the string (possibly one character at a time) all of the necessary 
conversions will be taken care of for you.  For instance, if you're 
trying to write to a serial port, you can simply write characters to it.

Keep in mind that, in a language like C, a character is simply a 
single-byte unsigned integer type.  Routines that pass characters back 
and forth often *look* like they're passing a hex number (i.e. 0x32), 
but it's actually a char -- or rather, in those languages there's no 
difference between that hex number and the char.  Python does actually 
treat characters and strings as first-class types, but it knows how 
the underlying C routines look at characters, too.  So usually, if 
you're trying to pass ascii codes around, you just want to use normal 
Python characters.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list