Vani Polnedi
Vani Polnedi

Reputation: 605

Hex to String convertion

I have a string like this :

message='भी मिलता था। सरोपा #variable# भेंट करना अब शायद सिर्फ सिख परंपरा में ही बचा समाज की #variable# गहराई नापते रहे हैं गुणाधर'

I have converted this string to hex using

output = ''.join(hex(ord(c)) for c in message) 

output1 = output.replace('0x','0')

and the final hex is :

'092d0940020092e093f09320924093e0200925093e096402009380930094b092a093e02002307606107206906106206c065023020092d09470902091f020091509300928093e0200905092c0200936093e092f09260200938093f0930094d092b0200938093f0916020092a09300902092a0930093e020092e0947090202009390940020092c091a093e0200938092e093e091c0200915094002002307606107206906106206c065023020091709390930093e09080200928093e092a09240947020093009390947020093909480902020091709410923093e09270930'

How can I get back my original string from encoded hex?

OR How can I get back my original string from output(without replacing)?

Upvotes: 1

Views: 219

Answers (2)

BlueSheepToken
BlueSheepToken

Reputation: 6099

As some commentaries already specified, it is impossible to decode if you replace 0x by 0, the closest I could get is the following

# Deencoding
hexs = []
tmp = ''
for i in range(len(output1)):
    if i < len(output1) - 1 and output1[i] == '0' and output1[i+1] != '0':
        hexs.append(tmp)
        tmp = ''
    else:
        tmp += output1[i]
if tmp != '':
    hexs.append(tmp)

print(''.join(chr(int(c,16)) for c in hexs[1:]))

Which will fail because in your hex code you have 902, how do you determine if it is 2 characters 9 and 2 or only one 902?

If you can keep the 0x, you can simply use the other commands to get it back with int and chr as follow

print(''.join(chr(int(c, 16)) for c in output[2:].split('0x')))

But the best way to do what you want is probably to use binascii

Upvotes: 1

Mntfr
Mntfr

Reputation: 513

The binascii library already has functions for coding and encoding in hex

import binascii

message='भी मिलता था। सरोपा #variable# भेंट करना अब शायद सिर्फ सिख परंपरा में ही बचा समाज की #variable# गहराई नापते रहे हैं गुणाधर'
messageEncoded = binascii.hexlify(message.encode())
print(messageEncoded)

messageDecoded =  binascii.unhexlify(messageEncoded)
print(messageDecoded.decode())

Upvotes: 2

Related Questions