Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python UCS2 decoding from hex string

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 ?

like image 896
Grous Avatar asked Jan 08 '14 17:01

Grous


1 Answers

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

>>> 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 Еще
like image 54
falsetru Avatar answered Sep 27 '22 19:09

falsetru