天天看點

python十進制轉換,将十進制轉換為十六進制python

python十進制轉換,将十進制轉換為十六進制python

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 !

解決方案>>> 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.