CS机器人可以通过指令socket_read_byte_list(4) 读取定长的字节数组。
例如上位机发来的数据是0x3F,0x80,0x00,0x00,则通过socket_read_byte_list(4) 接收到数据为[4,63,128,0,0](第一个数据为接收到的数据长度,若后续数据有未接收到的,则对应值为-1)
对于收到的数组,可以根据用户定义的类型(float,int16/int32)进行解析。
如果要将float,int16/int32等类型拆分成字节数组,也可以使用以下代码进行拆分,并使用指令socket_send_byte_list([1, 0x3, 0x2E, 3])进行发送
import struct
def Bytes2Float(d,BigEndian=False):
# 输入4个字节数据,转化为对应的32位的实数,默认使用小端编码,使用大端编码添加参数BigEndian为True
if BigEndian ==True:
return struct.unpack('<f', struct.pack('4B', *d))[0]
else:
return struct.unpack('>f', struct.pack('4B', *d))[0]
def Bytes2Int32(d,BigEndian=False):
# 输入4个字节数据,转化为对应的32位的带符号整数,默认使用小端编码,使用大端编码添加参数BigEndian为True
if BigEndian ==True:
return struct.unpack('<i', struct.pack('4B', *d))[0]
else:
return struct.unpack('>i', struct.pack('4B', *d))[0]
def Bytes2Int16(d,BigEndian=False):
# 输入2个字节数据,转化为对应的16位的带符号整数,默认使用小端编码,使用大端编码添加参数BigEndian为True
if BigEndian ==True:
return struct.unpack('<h', struct.pack('2B', *d))[0]
else:
return struct.unpack('>h', struct.pack('2B', *d))[0]
def Float2Bytes(d,BigEndian=False):
# 输入32位的实数,转化位对应4个字节数据,默认使用小端编码,使用大端编码添加参数BigEndian为True
if BigEndian ==True:
return list(struct.unpack('4B',struct.pack('f',d)))
else:
return list(struct.unpack('4B',struct.pack('>f',d)))
def Int322Bytes(d,BigEndian=False):
# 输入32位带符号整数,转化位对应4个字节数据,默认使用小端编码,使用大端编码添加参数BigEndian为True
if BigEndian ==True:
return list(struct.unpack('4B',struct.pack('<i',d)))
else:
return list(struct.unpack('4B',struct.pack('>i',d)))
def Int162Bytes(d,BigEndian=False):
# 输入16位带符号整数,转化位对应2个字节数据,默认使用小端编码,使用大端编码添加参数BigEndian为True
if BigEndian ==True:
return list(struct.unpack('2B',struct.pack('<h',d)))
else:
return list(struct.unpack('2B',struct.pack('>h',d)))
a = Float2Bytes(1.0)
# 默认使用小端编码,输出数据如下
# a = [0x3F,0x80,0x00,0x00]
a = Float2Bytes(1.0,True)
# 使用大端编码,输出数据如下
# a = [0x00,0x00,0x80,0x3F]
b = Bytes2Float( [0x3F,0x80,0x00,0x00])
# 默认使用小端编码,输出数据如下
# b = 1.0
b = Bytes2Float( [0x3F,0x80,0x00,0x00],True)
# 使用大端编码,输出数据如下
# b = 4.600602988224807e-41