Data comes from outside of the program as long array has to be converted into byte array. how to do that efficiently? As well, is there are way to select type of convertion as Little Endian or Big Endian.
1 Answer
You can do like this to convert a long array to a byte array:
bool isLittleEndian = true;
byte[] data = new byte[longData.Length * 8];
int offset = 0;
foreach (long value in longData) {
byte[] buffer = BitConverter.GetBytes(value);
if (BitConverter.IsLittleEndian != isLittleEndian) {
Array.Reverse(buffer);
}
buffer.CopyTo(data, offset);
offset += 8;
}
This is usually efficient enough. If you need it to be faster, you should use pointers in an unsafe code block.
3 Comments
baraban
do you think is possible to use unmanaged memcpy in case if input array is IsLittleEndian? Is there are any sample on how to do that?
Guffa
@baraban: If the source and destination endianess is the same, you can use unmanaged block copy.
Guffa
@baraban: Yes, that seems to be usable.
longin the source array should become 8 bytes in the destination array? (And that the conversion process should be capable of handling different endian-ness?)