Python Forum
convert result to hex ascii - 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: convert result to hex ascii (/thread-40014.html)



convert result to hex ascii - Jusufs - May-19-2023

Hi.
How to convert in Python3 sets of unsigned integer 16 bits to ASCII equivalent like picture please ?
Input is a 16bit unsigned int witch represents two ASCII chars.
Result should be a string with inverted bytes (not 6A338F67, but A633F876).
Thanks,

Jozef
[attachment=2374]


RE: convert result to hex ascii - deanhystad - May-19-2023

Use int() to convert numeric strings to int objects.
print(int("0x3846", 16)) (str, base)
Output:
14406
Python does not have 16 bit (or any fixed number of bits) ints, so signed/unsigned is not a thing in Python.


RE: convert result to hex ascii - Jusufs - May-19-2023

(May-19-2023, 11:03 AM)deanhystad Wrote: Use int() to convert numeric strings to int objects.
print(int("0x3846", 16)) (str, base)
Output:
14406
Python does not 16 bit (or any fixed number of bits) ints, so signed/unsigned is not a thing in Python.

Thanks but my source is your result
Source: 13889
Result ASCII hex code: 6A = ASCII 6 as 0x36 and A as 0x41

The first step is convert 13889 to 0x3641 and then to ASCII string 6A and finally swap string result to A6


RE: convert result to hex ascii - buran - May-19-2023

n=13889
print(bytes.fromhex(f'{n:02X}').decode())
print(bytes.fromhex(f'{n:02X}').decode()[::-1])
Output:
6A A6



RE: convert result to hex ascii - deanhystad - May-19-2023

Ok, I went the wrong direction.

13889 -> bytes = (0x36, 0x41) or (54, 65) -> ascii characters = ("6", "a") -> string = "6a"

number = 13889
as_bytes = number.to_bytes(2, "big")
as_ascii = "".join(chr(b) for b in as_bytes)
print(as_ascii)
Output:
6a



RE: convert result to hex ascii - Jusufs - May-19-2023

(May-19-2023, 11:28 AM)buran Wrote:
n=13889
print(bytes.fromhex(f'{n:02X}').decode())
print(bytes.fromhex(f'{n:02X}').decode()[::-1])
Output:
6A A6

Thank you very much for rapid help, this is it !!! Smile


RE: convert result to hex ascii - deanhystad - May-19-2023

Of course, decode(). So many nice tools in Python.
n = 13889
print(n.to_bytes(2, "big").decode())
print(n.to_bytes(2, "little").decode())
Output:
6A A6