Python中的字节操作

字节与整形互转

int.from_bytes (返回 int)

    a = bytes([0x00, 0x01, 0x22, 0x71])  # 74353 = 0x00012271
    # 这里的是以字节流的形式判断大小端,高位在前,所以是大端
    print( int.from_bytes(a, byteorder="big", signed=False) )  # 输出 74353
    
    b = bytes([0xff, 0xfe, 0xdd, 0x8f])	 # -74353 = 0xfffedd8f
    print( int.from_bytes(b, byteorder="big", signed=True) ) # 输出 -74353

    c = bytes([0xfe, 0xdd, 0x8f])
    # 支持任意字节长度,本质是判断最高的符号位
    print( int.from_bytes(c, byteorder="big", signed=True) ) # 输出 -74353

int.to_bytes (返回bytes)

    d = 74353
    print(d.to_bytes(4, byteorder="big", signed=False)) # 输出 b'\x00\x01"q' 等价于 bytes([0x00, 0x01, 0x22, 0x71])
    
    e = -74353
    print(e.to_bytes(4, byteorder="big", signed=True))  # 输出 b'\xff\xfe\xdd\x8f'

    f = -74353
    # 可以设置返回bytes的长度,如果过小会报错
    print(f.to_bytes(3, byteorder="big", signed=True))  # 输出 b'\xfe\xdd\x8f'

整形与2/8/16进制字符串互转

bin() otc() hex() (返回str)

    a = 78
    print(bin(a))			# 输出 0b1001110
    print(oct(a))			# 输出 0o116
    print(hex(a))			# 输出 0x4e
    print(hex(a).upper()) 	 # 输出 0x4E

int(x, n) (n = 2,8,16) (返回int)

    print(int("0b1001110", 2))
    print(int("0o116", 8))
    print(int("0x4e", 16))
    
    # 去掉前缀
    print(int("1001110", 2))
    print(int("116", 8))
    print(int("4e", 16))
    
    # 以上均输出 78

字节流和hex字符串互转

bytes.hex() bytearray.hex() (返回str)

    a = b"hello wrold!"
    print(a.hex())							# 68656c6c6f2077726f6c6421
    print(a.hex(" "))						# 68 65 6c 6c 6f 20 77 72 6f 6c 64 21
    print(a.hex(sep=":", bytes_per_sep=1))	  # 68:65:6c:6c:6f:20:77:72:6f:6c:64:21
    print(a.hex(sep=" ", bytes_per_sep=2))    # 6865 6c6c 6f20 7772 6f6c 6421

bytes.fromhex (返回bytes)

    print(bytes.fromhex("68656c6c6f2077726f6c6421"))			# 输出 b'hello wrold!'
    print(bytes.fromhex("68 65 6c 6c 6f 20 77 72 6f 6c 64 21"))	 # 输出 b'hello wrold!'

你可能感兴趣的:(python,嵌入式,单片机)