• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

deja-s

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

字符串与二进制互相转换(UTF-8编码)

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)
代码来源:华为云社区,具体地址忘了

posted on 2022-05-10 20:37  DJVQ  阅读(2053)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3