#创建10个字节 someData=bytes(10)
someInt=int(1024) byteData=someInt.to_bytes(4,byteorder='little',signed=True) gotInt=int.from_bytes(byteData,byteorder='little',signed=True)
import struct someFloat=float(3.14) #默认长度是4个字节 floatData=struct.pack('f',someFloat) #'f'就像是格式描述字符串 gotFloat=struct.unpack('f',floatData) # 一次转换多个 nums = [3.14, 2.71, 1.62] byte_data = struct.pack('3f', *nums) # 转换为 3 个 32 位浮点数 print(byte_data) # 使用'd'表示 double 一般是8字节 # 使用'>' '<' 表达大小端 比如 '<f'
someStr='Hello' #编码 strData=someStr.encode('utf-8') #解码 gotStr=strData.decode('utf-8') # 为了更方便传递到C 可能使用ascii编码更好
# AI # 方法1 b1 = b"hello" b2 = b" " b3 = b"world" # 拼接 result = b1 + b2 + b3 print(result) # 输出: b'hello world' # 方法2 byte_list = [b"hello", b" ", b"world"] # 拼接 result = b"".join(byte_list) print(result) # 输出: b'hello world'
AI:
转换为bytes
# AI # 创建一个 bytearray ba = bytearray(b"example data") # 转换为 bytes b = bytes(ba) # 转换为 bytes b = ba.tobytes()