Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
int to hex
#1
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
Reply
#2
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
>>>
Reply
#3
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'
Reply
#4
see: https://docs.python.org/3/library/functi...func-bytes
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020