Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
convert result to hex ascii
#1
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]

Attached Files

Thumbnail(s)
   
Reply
#2
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.
Reply
#3
(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
Reply
#4
n=13889
print(bytes.fromhex(f'{n:02X}').decode())
print(bytes.fromhex(f'{n:02X}').decode()[::-1])
Output:
6A A6
Jusufs likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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
Reply
#6
(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
Reply
#7
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
buran likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert SQLite Fetchone() Result to float for Math Extra 13 3,571 Aug-02-2022, 01:12 PM
Last Post: deanhystad
  convert hex encoded string to ASCII Skaperen 4 114,382 Oct-02-2016, 09:22 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

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