Convert binary to utf-8 in python

I have a binary code:   1101100110000110110110011000001011011000101001111101100010101000

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

+4
source share
4 answers

Pure version:

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

Reverse (from @ Robᵩ comment):

>>> '{:b}'.format(int(u'نقاب'.encode('utf-8').encode('hex'), 16))
1: '1101100110000110110110011000001011011000101001111101100010101000'
+10
source

Well, I have an idea: 1. Divide the string into octets 2. Convert the octet to hex using intlater chr  3. Attach them and decrypt the utf-8 string to Unicode

This code works for me, but I'm not sure if it prints because I don't have utf-8 in my console (Windows: P).

s = '1101100110000110110110011000001011011000101001111101100010101000'
u = "".join([chr(int(x,2)) for x in [s[i:i+8] 
                           for i in range(0,len(s), 8)
                           ]
            ])
d = u.decode('utf-8')

Hope this helps!

+3
source
>>> s='1101100110000110110110011000001011011000101001111101100010101000'
>>> print (''.join([chr(int(x,2)) for x in re.split('(........)', s) if x ])).decode('utf-8')
نقاب
>>> 

, :

>>> s=u'نقاب'
>>> ''.join(['{:b}'.format(ord(x)) for x in s.encode('utf-8')])
'1101100110000110110110011000001011011000101001111101100010101000'
>>> 
+3

:

def bin2text(s): return "".join([chr(int(s[i:i+8],2)) for i in xrange(0,len(s),8)])


>>> print bin2text("01110100011001010111001101110100")
>>> test
+1

All Articles