• python中unicode, hex, bin之间的转换


    python中unicode, hex, bin之间的转换


    背景 在smb中有个feature change notify, 需要改动文件权限dacl,然后确认是否有收到notify。一直得不到这个dacl的formal是什么样子的,于是pdb中打印出原始dacl,是个类似于x01x00x04的字符串str,然鹅无法用str的方法来操作它。

    需求 拿到特定的dacl位(wireshark中已确认为str的第34位11111,binx1f)并对它的最后一个bit位进行翻转。
    get到的只能是个str类型的x1f, 需转成bin,异或后再转回bytes


    尝试 decode / encode

    发现 这个奇怪的str 是unicode,尝试encode & decode
    后来,确认到,这只是在unicode 和 bytes之间的转换,并无法转为bin。


    尝试format , bin 等

    1. format

      format(0x12, '08b')  >>> '00010010'
      "{:08b}".format(0x12)  >>> '00010010'
      

      得到一个过长的字符串,无法对这个字符串进行异或操作,且无法对get到的str进行format操作

    2. bin

      bin(0x12) >>> '0b10010'
      得到一个 带着0b标识的字符串
      而且确认到,bin无法直接接收一个'x01''00010010'这样的字符串


    曲线救国,先转int再转bin,再异或

    1. 先转int

      beforeDACL[34] >>> 'x1f'
      ord(beforDACL[34]) >>> 31
      
    2. 再由int转为bin

      bin_dacl = bin(dacl)[2:] # '11111'
      这里的[2:]是由bin转换后的长度,本来是8位,只截取后面的几位,因为这个dacl的有效位只5位。

    3. 对bin的最后一位异或

      list_dacl = list(bin_dacl) # list之后得到的是str
      list_dacl[-1] = str(int(list_dacl[-1]) ^ 1)  # 将得到的str int后,异或,然后再转回str
      up_list_dacl = ''.join(list_dacl) #  拼接回原来的str
      
    4. 转回最初的格式x01

      up_dacl = int(up_list_dacl, 2)  # 30
      # Convert back to the original format
      set_dacl = chr(up_dacl) # >>> 'x1e' 由int型转回初始类型
  • 相关阅读:
    【Node.js 自己封装的库 http_parse, libuv】
    select遍历list默认选中初始值
    mybatis入门基础----高级映射(一对一,一对多,多对多)
    工具类 | window批处理杀死指定端口进程
    eclipse 关闭控制台 自动弹出
    mybatis的jdbcType和javaType、oracle,MySQL的对应类型
    mysql 创建表格 AUTO_INCREMENT
    Linux shell脚本启动 停止 重启jar包
    Tomcat结合nginx使用小结
    集成maven和Spring boot的profile功能
  • 原文地址:https://www.cnblogs.com/vivivi/p/10464450.html
Copyright © 2020-2023  润新知