1

I'm getting confused with python, hex, int, LSB. I have a number. Let's say

number=1000

i write it in hex format :

new = '%08x' % number
#000003e8

Now i need to print these number in these format:

\xe8\x03\x00\x00

Any help would be appreciated! Thanks!

Dev_dio
  • 21
  • 3
  • You mean you want to convert it to *bytes* instead? Then use `struct.pack()`. – Martijn Pieters Dec 08 '14 at 12:20
  • There is a thread related to a similar problem. [How to convert integer value to array of four bytes in python](http://stackoverflow.com/questions/6187699/how-to-convert-integer-value-to-array-of-four-bytes-in-python). – erik-e Dec 08 '14 at 12:28

3 Answers3

1

You can use struct.pack for that:

print repr(struct.pack("I", 1000))
Tzach
  • 12,889
  • 11
  • 68
  • 115
  • Perfect! Thanks that is exactly what i need! But it print in ' ' ('\xe8\x03\x00\x00') Which i don't want! IS there a way to get rid of them? – Dev_dio Dec 08 '14 at 12:34
  • Found it: string = string1.replace("'", ""). Thanks for your help!! – Dev_dio Dec 08 '14 at 12:43
0

That is not "hex" format.

What you want is the string that consists of the code points ("characters") whose values come from the bytes of the number.

You can do this in many ways, one is using chr().

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Why can't you simply say:

num = 1000
num.to_bytes(4, 'little')

like I suggested here?

charlie80
  • 806
  • 1
  • 7
  • 17