Python Forum
int to hex - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: int to hex (/thread-8896.html)



int to hex - pythonper - Mar-12-2018

Hello,
I am trying to convert and array of ints to hexadecimal numbers with the format as b'\x50\x15\'
When I use the struct.pack(">H", int) most numbers looks ok, but some get turned into ascii characters..
For example the int value 3360 becomes b' \r' and not b'\x0d\x20'

Another example:
import struct
minnepls=struct.pack(">i", 20500)
print(minnepls)
Output:
b'\x00\x00P\x14'
Is there any way to get this to the format b'\x50\x15\x00'?
I'm using a assert len(thisvalue) which is failing on these values.

Any tips would be appreciated!

-Per


RE: int to hex - Larz60+ - Mar-12-2018

Use a format statement
>>> minnepls = 1234
>>> print("minnepls Hex: {0:x}".format(minnepls))
minnepls Hex: 4d2
>>> print("minnepls Octal: {0:o}".format(minnepls))
minnepls Octal: 2322
>>> print("minnepls Decimal: {0:}".format(minnepls))
minnepls Decimal: 1234
>>>
Or if using python 3.6+:
>>> minnepls = 1234
>>> print(f"minnepls Hex: {minnepls|0:x}")
minnepls Hex: 4d2
>>> print(f"minnepls Octal: {minnepls|0:o}")
minnepls Octal: 2322
>>> print(f"minnepls Decimal: {minnepls|0:}")
minnepls Decimal: 1234
>>>



RE: int to hex - pythonper - Mar-14-2018

Thank you for the quick reply, Larz.
The number conversion between int,hex etc seems ok. Int 3360 becomes hex 0xd20. How would you convert it to b'\x0d\x20' ? When running struct it just becomes b' \r'

#print(struct.pack("<H", 3360))
Output:
b' \r'



RE: int to hex - Larz60+ - Mar-14-2018

see: https://docs.python.org/3/library/functions.html#func-bytes