I need to get values in UInt16
and UInt64
as Byte[]
. At the moment I am using BitConverter.GetBytes
, but this method gives me a new array instance each time.
I would like to use a method that allow me to "copy" those values to already existing arrays, something like:
.ToBytes(UInt64 value, Byte[] array, Int32 offset);
.ToBytes(UInt16 value, Byte[] array, Int32 offset);
I have been taking a look to the .NET source code with ILSpy, but I not very sure how this code works and how can I safely modify it to fit my requirement:
public unsafe static byte[] GetBytes(long value)
{
byte[] array = new byte[8];
fixed (byte* ptr = array)
{
*(long*)ptr = value;
}
return array;
}
Which would be the right way of accomplishing this?
Updated: I cannot use unsafe code. It should not create new array instances.
BinaryWriter can be a good solution.
It's useful when you need to convert a lot of data into a buffer continuously
or when you just want to write to a file, that's the best case to use BinaryWriter.
You can do like this:
Usage:
You can set offset only in bytes.
If you want managed way to do it:
Or you can fill values by yourself:
It seems that you wish to avoid, for some reason, creating any temporary new arrays. And you also want to avoid unsafe code.
You could pin the object and then copy to the array.
Now that .NET has added
Span<T>
support for better working with arrays, unmanaged memory, etc without excess allocations, they've also added System.Buffer.Binary.BinaryPrimitives.This works as you would want, e.g. WriteUInt64BigEndian has this signature:
which avoids allocating.
You say you want to avoid creating new arrays and you cannot use unsafe. Either use Ulugbek Umirov's answer with cached arrays (be careful with threading issues) or: