UTF-8编码格式:
n |
Unicode符号范围 |
UTF-8编码方式 |
1 |
0000 0000 - 0000 007F |
0xxxxxxx |
2 |
0000 0080 - 0000 07FF |
110xxxxx 10xxxxxx |
3 |
0000 0800 - 0000 FFFF |
1110xxxx 10xxxxxx 10xxxxxx |
4 |
0001 0000 - 0010 FFFF |
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
5 |
0020 0000 - 03FF FFFF |
111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
6 |
0400 0000 - 7FFF FFFF |
1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
def constLenBin(int):
# 由于使用utf-8编码,utf-8编码最少是一个字节也就是8位,所以需要去掉 bin() 返回的二进制字符串中的 '0b',并在左边补足 '0' 直到字符串长度为 8
return '0'*(8-(len(bin(int))-2)) + bin(int).replace('0b','')
def string2binary(str):
return ''.join(map(constLenBin, bytearray('你好hello', 'utf-8')))
def binary2string(binary):
index = 0
string = []
# 每8位取后6位
rec = lambda x, i: x[2:8] + (rec(x[8:], i-1) if i > 1 else '') if x else ''
# 前8位取前四位加上,后n*8位取后六位
fun = lambda x, i: x[i+1:8] + rec(x[8:], i-1)
while index + 1 < len(binary):
chartype = binary[index:].index('0')
length = chartype * 8 if chartype else 8
string.append(chr(int(fun(binary[index:index + length], chartype), 2)))
index += length
return ''.join(string)
代码来源:华为云社区,具体地址忘了