简体   繁体   中英

Convert byte[] array to a short[] array with half the length

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.

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM