3

I have a byte[200] that is read from a file, representing a short[100] in little-endian format. This is how I read it:

using (FileStream fs = new FileStream(_path, FileMode.Open, FileAccess.Read))
{
    //fs.Seek(...)
    byte[] record = new byte[200];
    fs.Read(record, 0, record.Length);

    short[] target = new short[100];
    // magic operation that fills target array
}

I don't know what to put in "magic operation". I've read about BitConverter, but it doesn't seem to have a BitConverter.ToShort operation. Anyway, BitConverter seems to convert in a loop, whereas I would appreciate some way to "block copy" the whole array at once, if possible.

1 Answer 1

3

I think you're looking for Buffer.BlockCopy.

Buffer.BlockCopy(record, 0, target, 0, record.Length);

I believe that will preserve the endianness of the architecture you're on - so it may be inappropriate in some environments. You might want to abstract this into a method call which can check (once) whether or not it does what you want (e.g. by converting {0, 1} and seeing whether the result is {1} or {256}) and then either uses Buffer.BlockCopy or does it "manually" in a loop if necessary.

10
  • @ScottChamberlain: If what is little-endian? The processor architecture? If so, I agree. Edited.
    – Jon Skeet
    Nov 20, 2014 at 16:00
  • Thanks for the answer. The bytes in the file are required to be in little-endian format. And I want to believe every common PC is little-endian too. Gonna test this right now. Nov 20, 2014 at 16:06
  • Buffer.BlockCopy just copies the doesn't check/change endiannes. it is like memcpy
    – bansi
    Nov 20, 2014 at 16:08
  • Am I confused? The endianess of the source will be the same as the target. Is it not a question of byte order? I think this just works.
    – Jodrell
    Nov 20, 2014 at 16:09
  • 1
    @Jodrell: It's a matter of the endianness of the original data vs the endianness of the machine the code is running on. The OP knows that the data is actually little-endian... if uses that data on a machine which is big-endian, he'll end up with the wrong results. You say "Is it not a question of byte order" as if that's different from endianness...
    – Jon Skeet
    Nov 20, 2014 at 16:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.