在 C# 中将字节数组转换为短数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1104599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert byte array to short array in C#
提问by williamtroup
I'm currently reading a file and wanted to be able to convert the array of bytes obtained from the file into a short array.
我目前正在读取一个文件,并希望能够将从文件中获得的字节数组转换为一个短数组。
How would I go about doing this?
我该怎么做呢?
采纳答案by jason
One possibility is using Enumerable.Select
:
一种可能性是使用Enumerable.Select
:
byte[] bytes;
var shorts = bytes.Select(b => (short)b).ToArray();
Another is to use Array.ConvertAll
:
另一种是使用Array.ConvertAll
:
byte[] bytes;
var shorts = Array.ConvertAll(bytes, b => (short)b);
回答by Philippe Leybaert
short[] wordArray = Array.ConvertAll(byteArray, (b) => (short)b);
回答by Muad'Dib
byte[] bytes;
var shorts = bytes.Select(n => System.Convert.ToInt16(n)).ToArray();
回答by Muad'Dib
A shorthard is a compound of two bytes. If you are writing all the shorts to the file as true shorts then those conversions are wrong. You must use two bytes to get the true short value, using something like:
shorthard 是两个字节的组合。如果您将所有短裤作为真正的短裤写入文件,那么这些转换是错误的。您必须使用两个字节来获取真正的短值,使用类似的方法:
short s = (short)(bytes[0] | (bytes[1] << 8))
回答by Gabriel
short value = BitConverter.ToInt16(bytes, index);
回答by steppenwolfe
Use Buffer.BlockCopy.
Create the short array at half the size of the byte array, and copy the byte data in:
创建字节数组一半大小的短数组,并将字节数据复制到:
short[] sdata = new short[(int)Math.Ceiling(data.Length / 2)];
Buffer.BlockCopy(data, 0, sdata, 0, data.Length);
It is the fastest method by far.
这是迄今为止最快的方法。
回答by Wolfgang Roth
I dont know, but I would have expected another aproach to this question. When converting a sequence of bytes into a sequence of shorts, i would have it done like @Peter did
我不知道,但我会期待另一个方法来解决这个问题。将字节序列转换为短裤序列时,我会像@Peter 那样做
short s = (short)(bytes[0] | (bytes[1] << 8))
or
或者
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.
但是OP没有提到他对短裤的使用或文件中短裤的定义。在他的情况下,将字节数组转换为短数组是没有意义的,因为它需要两倍的内存,而且我怀疑在其他地方使用时是否需要将字节转换为短数组。