Python Forum

Full Version: Converting from HEX to ANSI
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Image: sHuf4GL]

I am basically searching for a script to convert a Hex string to Windows(ANSI)
do you mean text (ASCII) ?
Do you mean ASCII? This should be pretty easy. Loop over the string two characters at a time, call int() with those two characters and 16, then use chr() to convert the generated number into a character.
(Oct-23-2018, 11:55 PM)micseydel Wrote: [ -> ]Do you mean ASCII? This should be pretty easy. Loop over the string two characters at a time, call int() with those two characters and 16, then use chr() to convert the generated number into a character.

(Oct-23-2018, 11:53 PM)Larz60+ Wrote: [ -> ]do you mean text (ASCII) ?

I think i am confusing between ASCII and 'Windows-1252'.
That aside, let's say i want to convert the following string ch='E4BC716838B15CE6FCD5' to this string onscreen "ä¼qh8±\æüÕ"
Here is what i did:

#Convert to: "ä¼qh8±\æüÕ" #
  ch='E4BC716838B15CE6FCD5' 
  for i in range(1,(len(ch)//2)+1):
      ph=''
      ph=ch[2*i-2:2*i]        #the two char at a time string
      x=bytes.fromhex(ph)     #int(x, 16) doesn't seem to work (E4,BC.. are probably the cause)
      print(x,end='')
What the Shell shows is:
b'\xe4'b'\xbc'b'q'b'h'b'8'b'\xb1'b'\\'b'\xe6'b'\xfc'b'\xd5'

Which should have been(atleast what i want to get):
b'ä¼qh8±\æüÕ'

(My main reason for writing this script is converting 'hex string' to 'whatever these type of characters are_äæB©ó¾‡_')
(Also if possible, tell me everything about the characters)
(Oct-24-2018, 11:51 AM)Blackklegend Wrote: [ -> ]Which should have been(atleast what i want to get):
b'ä¼qh8±\æüÕ'
There is mbcs encoding for Windows that can convert between ANSI and Unicode.
>>> s = b'\xe4'b'\xbc'b'q'b'h'b'8'b'\xb1'b'\\'b'\xe6'b'\xfc'b'\xd5'
>>> d = s.decode('mbcs')
>>> d
'ä¼qh8±\\æüÕ'
>>> print(d)
ä¼qh8±\æüÕ
>>> 'ä¼qh8±\æüÕ' == d
True
(Oct-24-2018, 01:31 PM)snippsat Wrote: [ -> ]
(Oct-24-2018, 11:51 AM)Blackklegend Wrote: [ -> ]Which should have been(atleast what i want to get):
b'ä¼qh8±\æüÕ'
There is mbcs encoding for Windows that can convert between ANSI and Unicode.
>>> s = b'\xe4'b'\xbc'b'q'b'h'b'8'b'\xb1'b'\\'b'\xe6'b'\xfc'b'\xd5'
>>> d = s.decode('mbcs')
>>> d
'ä¼qh8±\\æüÕ'
>>> print(d)
ä¼qh8±\æüÕ
>>> 'ä¼qh8±\æüÕ' == d
True

Thank you for the tip but I went on an did it manually before reading your reply.

(Oct-23-2018, 11:55 PM)micseydel Wrote: [ -> ]Do you mean ASCII? This should be pretty easy. Loop over the string two characters at a time, call int() with those two characters and 16, then use chr() to convert the generated number into a character.

After reading this carefully I got the following code:
ch="E4BC716838B15CE6FCD5"
for i in range(1,(len(ch)//2)+1):
    Lh=''
    Lh=ch[2*i-2:2*i]
    x = int(Lh,16)
    print(chr(x),end=' ')