0

我是在 as3 中使用 ByteArray 的菜鸟,需要一些帮助。我试图在 as3 中重现这个“Header”函数,从 C# 函数返回一个 ByteArray(下面提供的代码)。谁能指出我正确的方向?

我到了这一点,不知道如何继续:

 private function header():ByteArray
    {
        var header:ByteArray = new ByteArray();
        header.writeUTFBytes("A");
        header.writeUTFBytes("B");
        header.writeUTFBytes("C");
        header.writeUTFBytes("D");
            ...                
    }

谢谢

private enum PacketType
    {
        PtHelo = 0x01,
        PtBye = 0x02,
        PtButton = 0x03,
        PtMouse = 0x04,
    }

private const byte bv = 2;
private const byte mv = 0;

private byte[] Header(PacketType packetType, int numberOfPackets, int currentPacket, int payloadSize)
    {
        var header = new byte[HeaderSize];
        header[0] = (byte)'A';
        header[1] = (byte)'B';
        header[2] = (byte)'C';
        header[3] = (byte)'D';
        header[4] = bv;
        header[5] = mv;
        if (currentPacket == 1)
        {
            header[6] = (byte)(((ushort)packetType & 0xff00) >> 8);
            header[7] = (byte)((ushort)packetType & 0x00ff);
        }
        else
        {
            header[6] = ((ushort)PacketType.PtBlob & 0xff00) >> 8;
            header[7] = (ushort)PacketType.PtBlob & 0x00ff;
        }
        header[8] = (byte)((currentPacket & 0xff000000) >> 24);
        header[9] = (byte)((currentPacket & 0x00ff0000) >> 16);
        header[10] = (byte)((currentPacket & 0x0000ff00) >> 8);
        header[11] = (byte)(currentPacket & 0x000000ff);
        header[12] = (byte)((numberOfPackets & 0xff000000) >> 24);
        header[13] = (byte)((numberOfPackets & 0x00ff0000) >> 16);
        header[14] = (byte)((numberOfPackets & 0x0000ff00) >> 8);
        header[15] = (byte)(numberOfPackets & 0x000000ff);
        header[16] = (byte)((payloadSize & 0xff00) >> 8);
        header[17] = (byte)(payloadSize & 0x00ff);
        return header;
    }
4

1 回答 1

0

头函数的其余部分基本上可以使用与 C# 版本相同的数组索引和位算术(仅删除强制转换)。但避免算术可能更简单:

header.endian = Endian.BIG_ENDIAN; // important for writing multibyte below
header.writeUTFBytes('ABCD');
header.writeByte(bv);
header.writeByte(mv);
if (...) {
    header.writeShort(packetType);
} else {
    header.writeShort(PtBlob); // PtBlob is a constant defined elsewhere
}
header.writeInt(currentPacket);
...

使用字节算术:

header.writeByte((packetType & 0xff00) >> 8);
header.writeByte(packetType & 0x00ff);

由于上面是从 写入两个字节packetType,所以它相当于一个 big-endian writeShort()

于 2013-08-07T21:52:46.570 回答