views:

474

answers:

4

Hi All,

Im building a server in python, i need to convert a decimal value to hex like this :

let's say the packet start by 4 bytes which define the packet lenght : 00 00 00 00 if the len(packet) = 255 we would send : 00 00 00 ff

Now my problem is that sometimes the packet is bigger than 256 as for example 336, then it would be : 00 00 01 50

i dont know how to do that in python, and i will really appreciate any help. Thanks !

+6  A: 
>>> import struct
>>> struct.pack(">i", 336)
'\x00\x00\x01P'

The struct module packs and unpacks python values into bytes. The ">i" format means big-endian 4-byte integer.

Ned Batchelder
A: 

I don't see what you're getting at with your examples, but if you just want to convert a base 10 number to a base 16 number in python, use hex().

Matt Ball
A: 

What about

"%0.8x" % data

Sample:

>>> print "%0.8x" % 366
0000016e

>>> print "%0.8x" % 336
00000150
Johannes Weiß
A: 

Thanks you very much everyone that's perfect !

n00bie
accept the answer, upvote if you like some, but close this one
Anurag Uniyal