Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting binary to utf-8 in python

I have a binary like this: 1101100110000110110110011000001011011000101001111101100010101000

and I want to convert it to utf-8. how can I do this in python?

like image 967
Aidin.T Avatar asked Oct 08 '13 18:10

Aidin.T


People also ask

How do you convert binary to text in Python?

Method #1: The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string. This ASCII code is then converted to string using chr() function.

What does encoding =' UTF-8 do in Python?

UTF-8 is a byte oriented encoding. The encoding specifies that each character is represented by a specific sequence of one or more bytes.


1 Answers

Cleaner version:

>>> test_string = '1101100110000110110110011000001011011000101001111101100010101000'
>>> print ('%x' % int(test_string, 2)).decode('hex').decode('utf-8')
نقاب

Inverse (from @Robᵩ's comment):

>>> '{:b}'.format(int(u'نقاب'.encode('utf-8').encode('hex'), 16))
1: '1101100110000110110110011000001011011000101001111101100010101000'
like image 170
Igonato Avatar answered Sep 20 '22 18:09

Igonato