ByteArray class for C#

本文关键字:for class ByteArray | 更新日期: 2023-09-27 18:20:23

我正在尝试将ActionScript 3中的一个函数转换为C#.NET.

我遇到的问题是如何在C#中正确使用ByteArrays。在As3中有一个特定的类,它已经拥有了我需要的大部分功能,但在C#中似乎不存在这种类型的东西,我无法理解它

这是As3的功能:

private function createBlock(type:uint, tag:uint,data:ByteArray):ByteArray
        {
            var ba:ByteArray = new ByteArray();
            ba.endian = Endian.LITTLE_ENDIAN;
            ba.writeUnsignedInt(data.length+16);
            ba.writeUnsignedInt(0x00);
            ba.writeUnsignedInt(type);
            ba.writeUnsignedInt(tag);
            data.position = 0;
            ba.writeBytes(data);
            ba.position = 0;
            return ba;  
        }

但据我所知,在C#中,我必须使用一个字节类型的普通数组,比如这个

byte[] ba = new byte[length];

现在,我研究了Encoding类、BinaryWriter和BinaryFormatter类,并研究了是否有人为ByteArrays创建了一个类,但没有成功。

有人能把我推向正确的方向吗?

ByteArray class for C#

您应该能够使用MemoryStreamBinaryWriter:的组合来完成此操作

public static byte[] CreateBlock(uint type, uint tag, byte[] data)
{
    using (var memory = new MemoryStream())
    {
        // We want 'BinaryWriter' to leave 'memory' open, so we need to specify false for the third
        // constructor parameter. That means we need to also specify the second parameter, the encoding.
        // The default encoding is UTF8, so we specify that here.
        var defaultEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier:false, throwOnInvalidBytes:true);
        using (var writer = new BinaryWriter(memory, defaultEncoding, leaveOpen:true))
        {
            // There is no Endian - things are always little-endian.
            writer.Write((uint)data.Length+16);
            writer.Write((uint)0x00);
            writer.Write(type);
            writer.Write(data);
        }
        // Note that we must close or flush 'writer' before accessing 'memory', otherwise the bytes written
        // to it may not have been transferred to 'memory'.
        return memory.ToArray();
    }
}

但是,请注意,BinaryWriter总是使用little-endian格式。如果您需要控制这一点,可以使用Jon Skeet的EndianBinaryWriter

作为这种方法的替代方案,您可以四处传递流,而不是字节数组(可能使用MemoryStream来实现),但您需要小心使用寿命管理,即在使用完流后,谁将关闭/处置流?(由于内存流不使用非托管资源,因此您可能不必关闭/处置内存流,但这并不完全令人满意。)

您想要一个字节流,然后从中提取数组:

using(MemoryStream memory = new MemoryStream())
using(BinaryWriter writer = new BinaryWriter(memory))
{
    // write  into stream
    writer.Write((byte)0); // a byte
    writer.Write(0f);      // a float
    writer.Write("hello"); // a string
    return memory.ToArray(); // returns the underlying array
}