How to convert a long array to an array of bytes?

Data comes from outside the program, since a long array must be converted to an array of bytes. how to do it effectively? Also, is there a way to choose a conversion type like Little Endian or Big Endian.

+3
source share
1 answer

You can do this to convert an array longto an array byte:

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 quite effective. If you want this to be faster, you should use pointers in an insecure block of code.

+4
source

All Articles