Decoding Python UCS2 from a hexadecimal string

I am using python 2.7 and need to decode a hexadecimal string into a unicode string. In php everything is just doing the following:

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

hexadecimal string for example    000A0033002004200430043404300440000A003400200417043D0430043A043E043C0441044204320430000A00350020041C04430437044B043A0430000A00380020041504490435should be

3 
4 
5 
8 

How to do this in python?

+4
source share
2 answers

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

>>> import binascii

>>> line = '000A0033002004200430043404300440000A003400200417043D0430043A043E043C0441044204320430000A00350020041C04430437044B043A0430000A00380020041504490435'
>>> binascii.unhexlify(line)
b'\x00\n\x003\x00 \x04 \x040\x044\x040\x04@\x00\n\x004\x00 \x04\x17\x04=\x040\x04:\x04>\x04<\x04A\x04B\x042\x040\x00\n\x005\x00 \x04\x1c\x04C\x047\x04K\x04:\x040\x00\n\x008\x00 \x04\x15\x04I\x045'
>>> print(binascii.unhexlify(line).decode('utf-16-be'))

3 
4 
5 
8 
+6
source
>>> line = '000A0033002004200430043404300440000A003400200417043D0430043A043E043C0441044204320430000A00350020041C04430437044B043A0430000A00380020041504490435'
>>> print unicode(line.decode("hex"), "utf-16-be").encode("utf8")

3 
4 
5 
8 
+3
source

All Articles