• (转)python之from_bytes、to_bytes


    原文:https://blog.csdn.net/PYTandFA/article/details/78741339

    https://python3-cookbook.readthedocs.io/zh_CN/latest/c03/p05_pack_unpack_large_int_from_bytes.html

    首先我们来看两个__builtin__函数

    num1 = int.from_bytes(b'12', byteorder = 'big')
    num2 = int.from_bytes(b'12', byteorder = 'little')
    print('(%s,'%'num1', num1, '),', '(%s,'%'num2', num2, ')')
    result:(num1, 12594 ), (num2, 12849 )
    byt1 = (1024).to_bytes(2, byteorder = 'big')
    byt2 = (1024).to_bytes(10, byteorder = 'big')
    byt3 = (-1024).to_bytes(10, byteorder= 'big')
    lis1 = ['byt1', 'byt2', 'byt3', 'byt4']
    lis2 = [byt1, byt2, byt3, byt4]
    lis3 = zip(lis1, lis2)
    dic = dict(lis3)
    print(dic)
    result:
    byt1': b'x04x00'
    byt2': b'x00x04x00x00x00x00x00x00x00x00'
    byt3': b'xffxffxffxffxffxffxffxffxfcx00'
    byt4': b'xffxffxffxffxffxffxffxffxfcx00'int.from_bytes()功能是将字节转化成int型数字'12'如果没有标明进制,看做ascii码值,'1' = 49 = 0011 0001, '2' = 50 = 0011 0010,如果byteorder = 'big', b'12' = 0010 0001 0010 0010 = 12594;如果byteorder = 'littlele', b'12' = 0011 0010 0011 0001 = 12849。第三个参数为signed表示有符号和无符号;(number).to_bytes()功能将整数转化成byte
    (1024).to_bytes(10, byteorder = 'big'),一个int型,4字节。1024 = 0000 0000 0000 0000 0000 0100 0000 0000,由于给定的是10,所以凑齐10个字节,高位用6个
    0000 0000占位,如果最后用16进制表示,1024 = b'x00x00x00x00x00x00x00x00x04x00
    在看一个例子:
    byt3 = (-1024).to_bytes(10, byteorder= 'big', signed = 'true'),由于signed = 'true', -1024 = 1000 ...(11) 0000 0000 0000 0000 0000 0100 0000 0000,符号位为1,...省略了
    11个0000,由于负数由补码表示,所以先求-1024的反码,即符号位不变,其他位0变1,1变0,得:1111 ...(11) 1111 1111 1111 1111 1111 1011 1111 1111,对反码 + 1,得到补码:
    1111 ...(11) 1111 1111 1111 1111 1111 1100 0000 0000,用16进制表示:xffxffxffxffxffxffxffxffxfcx00
    再举个例子:
    num3 = int.from_bytes(b'xf3x25', byteorder = 'little')
    f3 = 243(10进制)= 1111 0011,25 = 37(10进制)= 0010 0101,byteorder = 'little',字节的低位占主要作用, 得到:0010 0101 1111 0011,得到十进制:9715
    num3 = int.from_bytes(b'xf3x25', byteorder = 'big', signed = 'true')
    f3 = 243(10进制)= 1111 0011,25 = 37(10进制)= 0010 0101,byteorder = 'big',字节的高位占主要作用, 得到:1111 0011 0010 0101,signed = 'true',说明有符
    号,而且高位为1,所以用补码:1000 1100 1101 1011 即:-3291

  • 相关阅读:
    时统设备简介和标准汇总
    html页面元素铺满屏幕
    JavaScript之单线程
    JavaScript 内存模型
    数据-内存-变量
    python+selenium2自动化---通过js脚本给时间控件赋值
    Linux常用命令---文件创建、查找
    python+selenium2自动化---使用pytesseract和Pillow实现验证码识别
    python+selenium2自动化---屏幕截图
    Linux常用命令---find
  • 原文地址:https://www.cnblogs.com/liujiacai/p/9972780.html
Copyright © 2020-2023  润新知