我目前正在读取一个文件,并希望能够将从文件中获得的字节数组转换为一个短数组。
我该怎么做呢?
以字节数组的一半大小创建短数组,并将字节数据复制到:
short[] sdata = new short[(int)Math.Ceiling(data.Length / 2)];
Buffer.BlockCopy(data, 0, sdata, 0, data.Length);
这是迄今为止最快的方法。
一种可能性是使用Enumerable.Select
:
byte[] bytes;
var shorts = bytes.Select(b => (short)b).ToArray();
另一种是使用Array.ConvertAll
:
byte[] bytes;
var shorts = Array.ConvertAll(bytes, b => (short)b);
shorthard 是两个字节的组合。如果您将所有短裤作为真正的短裤写入文件,那么这些转换是错误的。您必须使用两个字节来获得真正的短值,使用类似:
short s = (short)(bytes[0] | (bytes[1] << 8))
short value = BitConverter.ToInt16(bytes, index);
我不知道,但我会期待另一种方法来解决这个问题。将字节序列转换为短裤序列时,我会像@Peter那样完成
short s = (short)(bytes[0] | (bytes[1] << 8))
或者
short s = (short)((bytes[0] << 8) | bytes[1])
depending on endianess of the bytes in the file.
But the OP didnt mention his usage of the shorts or the definition of the shorts in the file. In his case it would make no sense to convert the byte array to a short array, because it would take twice as much memory, and i doubt if a byte would be needed to be converted to a short when used elsewhere.
short[] wordArray = Array.ConvertAll(byteArray, (b) => (short)b);
byte[] bytes;
var shorts = bytes.Select(n => System.Convert.ToInt16(n)).ToArray();