bytes
Operation
# bytes
# 255不同进制的表示
# 0b11111111 255的2进制表示
# 0o377 255的8进制表示,for Python3
# 0xff 255的16进制表示
b_array = bytearray([0xff,255,0b11111111,0o377]) # bytearray会填充Bit为对应的数值 , bytearray 每个位置表示1Bit
b_array.append(0xff)
b_array.append(255) # bytearray中使用int, 范围0-255
# 转换bytearray 到 bytes
bytes_s = bytes(b_array)
# 从字符串转换到 bytes
bytes_s2 = "hello".encode("utf-8")
# 把16进制的字母转为16进制数
n = int("FF",16)
byte_n = n.to_bytes(1,"little") # 把数字转为bytes, 由于计算机中的int一般占4Bit, 所以转换时可以设置位数。
demo. convert MacAddress to byte
"""
mac 地址转换为byte
"""
def mac_hex(mac):
byte_array = bytearray()
for hex_str in mac.split("-"):
byte_array.append(int(hex_str,16))
return byte_array
mac = "00-15-5D-A8-E4-B9"
print(mac_hex(mac))