Byte oriented data types in python

John Machin sjmachin at lexicon.net
Sun Jan 25 22:16:40 CET 2009


On Jan 26, 2:28 am, Ravi <ra.ravi.... at gmail.com> wrote:
> On Jan 25, 12:52 am, "Martin v. Löwis" <mar... at v.loewis.de> wrote:
>
> > > packet_type (1 byte unsigned) || packet_length (1 byte unsigned) ||
> > > packet_data(variable)
>
> > > How to construct these using python data types, as int and float have
> > > no limits and their sizes are not well defined.
>
> > In Python 2.x, use the regular string type: chr(n) will create a single
> > byte, and the + operator will do the concatenation.
>
> > In Python 3.x, use the bytes type (bytes() instead of chr()).
>
> This looks really helpful thanks!

Provided that you don't take Martin's last sentence too literally :-)


| Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on win32
| >>> p_data = b"abcd" # Omit the b prefix if using 2.5 or earlier
| >>> p_len = len(p_data)
| >>> p_type = 3
| >>> chr(p_type) + chr(p_len) + p_data
| '\x03\x04abcd'

| Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
(Intel)] on win32
| >>> p_data = b"abcd"
| >>> p_len = len(p_data)
| >>> p_type = 3
| >>> bytes(p_type) + bytes(p_len) + p_data # literal translation
| b'\x00\x00\x00\x00\x00\x00\x00abcd'
| >>> bytes(3)
| b'\x00\x00\x00'
| >>> bytes(10)
| b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
| >>> bytes([p_type]) + bytes([p_len]) + p_data
| b'\x03\x04abcd'
| >>> bytes([p_type, p_len]) + p_data
| b'\x03\x04abcd'

Am I missing a better way to translate chr(n) from 2.x to 3.x? The
meaning assigned to bytes(n) in 3.X is "interesting":

2.X:
nuls = '\0' * n
out_byte = chr(n)

3.X:
nuls = b'\0' * n
or
nuls = bytes(n)
out_byte = bytes([n])

Looks to me like there was already a reasonable way of getting a bytes
object containing a variable number of zero bytes. Any particular
reason why bytes(n) was given this specialised meaning? Can't be the
speed, because the speed of bytes(n) on my box is about 50% of the
speed of the * expression for n = 16 and about 65% for n = 1024.

Cheers,
John



More information about the Python-list mailing list