Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert decimal to hex 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 !

like image 223
n00bie Avatar asked Mar 27 '26 08:03

n00bie


2 Answers

>>> 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.

like image 154
Ned Batchelder Avatar answered Mar 29 '26 21:03

Ned Batchelder


What about

"%0.8x" % data

Sample:

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

>>> print "%0.8x" % 336
00000150
like image 26
Johannes Weiss Avatar answered Mar 29 '26 23:03

Johannes Weiss