[Tutor] convert decimal to hex

Emil Styrke emil@lysator.liu.se
Mon Mar 3 17:28:06 2003

Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: quoted-printable

vicki@stanfield.net writes:

> I am working on a small Python script which sends data
> out on a serial port to a device and reads what that
> device sends back. What I send is in hex format as
> should be what I receive back. I should receive a
> "0x15) but I get what resembles a section break
> character in editing notation (=A7=A7). I am relatively
> sure of the port settings that I am using (and
> experimentation hasn't given me anything resembling
> what I expected anyway). Can anyone give me a clue as
> to how to proceed to fix this problem? I am using the
> serial module write and read commands. I tried readline
> as well. I can verify what is sent and received in
> another application that I have.=20

What you have received is probably a character with the ordinal value
0x15.  To convert character data to integers, you can use the ord()
function, and to convert a number to hex notation you can use the
hex() function.


>>> data =3D "hello"
>>> for char in data:
>>>     print hex(ord(char))

Note that hex() returns a string, not a number.

Note also that the same applies for writing to the device, so calling
something like write("0x15") won't work, as it will send the four
characters 0, x, 1 and 5 to the device.

> Thanks,
> --vicki

Content-Type: application/pgp-signature

Version: GnuPG v1.2.1 (GNU/Linux)