懂C#同时懂Python的来,帮我把C#这两个函数转成Python版的

public static byte[] EncodeMsg(int opCode, int subCode, object value)
{
       MemoryStream ms = new MemoryStream();
       BinaryWriter bw = new BinaryWriter(ms);
       bw.Write(opCode);
       bw.Write(subCode);
       //如果不等于null  才需要把object 转换成字节数据 存起来
       if (value != null)
       {
           byte[] valueBytes = EncodeObj(value);
           bw.Write(valueBytes);
       }
       byte[] data = new byte[ms.Length];
       Buffer.BlockCopy(ms.GetBuffer(), 0, data, 0, (int)ms.Length);
       bw.Close();
       ms.Close();
       return data;
}


public static byte[] EncodePacket(byte[] data)
{
      //内存流对象
      using (MemoryStream ms = new MemoryStream())
      {
           using (BinaryWriter bw = new BinaryWriter(ms))
           {
                //先写入长度
                bw.Write(data.Length);
                //再写入数据
                bw.Write(data);

                byte[] byteArray = new byte[(int)ms.Length];
                Buffer.BlockCopy(ms.GetBuffer(), 0, byteArray, 0, (int)ms.Length);

                return byteArray;
           }
       }
}

 

函数EncodeObj是怎么定义的呀?

其实描述函数的功能重新写,比从C#改写更容易。


def EncodeMsg(opCode, subCode, value):
    bo = opCode.to_bytes(4, byteorder='big')
    bs = subCode.to_bytes(4, byteorder='big')
    bv = bytearray(value, "UTF-8")
    b = bo + bs + bv
    return b

def EncodePacket(value):
    l = len(value)
    bl = l.to_bytes(4, byteorder='big')
    b = bl + value
    return b

bm = EncodeMsg(123, 4567890, "This is a test message")
print(bm)

bp = EncodePacket(bm)
print(bp)


# Output:
b'\x00\x00\x00{\x00E\xb3RThis is a test message'
b'\x00\x00\x00\x1e\x00\x00\x00{\x00E\xb3RThis is a test message'