[Tutor] how to see a number as two bytes

Alan Gauld alan.gauld at btinternet.com
Tue Oct 21 01:06:40 CEST 2008

"shawn bright" <nephish at gmail.com> wrote

> i have a script that needs to send a number as two bytes.
> how would i be able to see a number expressed as a hi byte and a lo 
> byte?

One way is to use the struct module.
It has the advantage of allowing selection of big endian(>) or little
endian(<) representation etc. The H symbol can be used for a short
integer - ie 2 bytes...


>>> import struct
>>> b = struct.pack(">H", 279)
>>> b
>>> b = struct.pack("<H", 279)
>>> b

Note that Python will print bytes with printable representations as
the character form but the data is still two bytes.

>>> struct.pack("H", 33)
>>> chr(33)


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list