convert decimal to hex python

2019-02-19 10:48发布

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 !

2条回答
够拽才男人
2楼-- · 2019-02-19 10:56

What about

"%0.8x" % data

Sample:

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

>>> print "%0.8x" % 336
00000150
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-19 11:17
>>> 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.

查看更多
登录 后发表回答