Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert long array into byte array?

Tags:

arrays

c#

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.

like image 654
baraban Avatar asked Sep 28 '26 09:09

baraban


1 Answers

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.

like image 135
Guffa Avatar answered Sep 29 '26 22:09

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!