ByteArray class for C #
I am trying to translate a function from ActionScript 3 to C # .NET.
I am having problems on how to use ByteArrays correctly in C #. There is a specific class for it in As3 that already has most of the functionality that I need, but nothing like this exists in C # and I can't wrap my head around it.
This is the As3 function:
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;
}
But from what I'm collecting, in C # I have to use a regular byte-type array like this
byte[] ba = new byte[length];
I have now looked at the Encoding Class, BinaryWriter and BinaryFormatter and inquired if anyone has created a class for ByteArrays with no luck.
Can someone nudge me in the right direction?
source to share
You have to do this using a combination of MemoryStream
and BinaryWriter
:
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();
}
}
Note, however, that it BinaryWriter
always uses the little-endian format. If you need to control this, you can use Jon SkeetEndianBinaryWriter
.
As an alternative to this approach, you can stream streams instead of byte arrays (perhaps using MemoryStream
to implement), but then you need to be careful about lifecycle management, i.e. who will close / delete the stream when done? (You might be able to get away without bothering to close / delete the memory stream as it doesn't use unmanaged resources, but that's not entirely satisfying IMO.)
source to share
You want to have a stream of bytes and then extract an array from it:
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
}
source to share