3

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.

3
  • 1
    Do you mean that every long in the source array should become 8 bytes in the destination array? (And that the conversion process should be capable of handling different endian-ness?) Commented May 22, 2012 at 15:10
  • @baraban....the data is a long array or just a long? Commented May 22, 2012 at 15:13
  • 1
    Please give an unambiguous example of a given input and what its output would be. Commented May 22, 2012 at 15:13

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@baraban: If the source and destination endianess is the same, you can use unmanaged block copy.
@baraban: Yes, that seems to be usable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.