declaring Hex in python

David Wahler dwahler at
Thu Nov 3 18:03:28 CET 2005

PythonAni... at wrote:
> I want to use some old C code such as
> #define GEN_STREAMTYPE_NULL          	      0x51
> I need to send this to a server, but it must be declared as a unsigned
> four byte constant.  I can not just send a string.  I love python, but
> am looking for information where I can declare this and then send it
> through a socket.
> Also are there any classes or methods which can manipulate what is
> returned, such as shifting bits returned.
> Thank-you

See the "struct" module (
for a couple of really useful functions. For example, you could use:

>>> def send4bytes(num):
...     mysocket.send(struct.pack("L", num))
>>> send4bytes(GEN_STREAMTYPE_NULL)

As for bit manipulation--it's built in, just like in C.

>>> hex(0x1234 & 0xFF)
>>> hex(0x34 << 8)

Hope this helps.

-- David

More information about the Python-list mailing list