14

我目前正在读取一个文件,并希望能够将从文件中获得的字节数组转换为一个短数组。

我该怎么做呢?

4

7 回答 7

65

使用Buffer.BlockCopy

以字节数组的一半大小创建短数组,并将字节数据复制到:

short[] sdata = new short[(int)Math.Ceiling(data.Length / 2)];
Buffer.BlockCopy(data, 0, sdata, 0, data.Length);

这是迄今为止最快的方法。

于 2010-10-30T18:27:10.570 回答
13

一种可能性是使用Enumerable.Select

byte[] bytes;
var shorts = bytes.Select(b => (short)b).ToArray();

另一种是使用Array.ConvertAll

byte[] bytes;
var shorts = Array.ConvertAll(bytes, b => (short)b);
于 2009-07-09T15:25:38.030 回答
5

shorthard 是两个字节的组合。如果您将所有短裤作为真正的短裤写入文件,那么这些转换是错误的。您必须使用两个字节来获得真正的短值,使用类似:

short s = (short)(bytes[0] | (bytes[1] << 8))
于 2009-08-09T00:31:24.367 回答
2
short value = BitConverter.ToInt16(bytes, index);
于 2010-04-30T12:52:05.977 回答
1

我不知道,但我会期待另一种方法来解决这个问题。将字节序列转换为短裤序列时,我会像@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.

于 2016-11-15T09:59:24.383 回答
0
 short[] wordArray = Array.ConvertAll(byteArray, (b) => (short)b);
于 2009-07-09T15:26:06.530 回答
-2
byte[] bytes;
var shorts = bytes.Select(n => System.Convert.ToInt16(n)).ToArray();
于 2009-07-09T15:28:13.780 回答