Python UCS2 decoding from hex string

Question:

I am using python 2.7 and need to decode hex string to unicode string.
In php all simple I make following:

$line=hex2bin($line);
$finish=iconv("UCS-2BE","UTF-8",$nline);

hex string for example
000A0033002004200430043404300440000A003400200417043D0430043A043E043C0441044204320430000A00350020041C04430437044B043A0430000A00380020041504490435 should be

3 Радар
4 Знакомства
5 Музыка
8 Еще

How do it in python ?

Asked By: Grous

||

Answers:

Use binascii.unhexlify, then use bytes.decode with utf-16-be encoding:

>>> import binascii

>>> line = '000A0033002004200430043404300440000A003400200417043D0430043A043E043C0441044204320430000A00350020041C04430437044B043A0430000A00380020041504490435'
>>> binascii.unhexlify(line)
b'x00nx003x00 x04 x040x044x040x04@x00nx004x00 x04x17x04=x040x04:x04>x04<x04Ax04Bx042x040x00nx005x00 x04x1cx04Cx047x04Kx04:x040x00nx008x00 x04x15x04Ix045'
>>> print(binascii.unhexlify(line).decode('utf-16-be'))

3 Радар
4 Знакомства
5 Музыка
8 Еще
Answered By: falsetru
>>> line = '000A0033002004200430043404300440000A003400200417043D0430043A043E043C0441044204320430000A00350020041C04430437044B043A0430000A00380020041504490435'
>>> print unicode(line.decode("hex"), "utf-16-be").encode("utf8")

3 Радар
4 Знакомства
5 Музыка
8 Еще
Answered By: ivan___b

Python3 / Without external libs:

>>> line = '000A0033002004200430043404300440000A003400200417043D0430043A043E043C0441044204320430000A00350020041C04430437044B043A0430000A00380020041504490435'
>>> output = bytes.fromhex(line).decode('utf-16-be')
>>> print(output)

3 Радар
4 Знакомства
5 Музыка
8 Еще
Answered By: maigre
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.