【IT专家】在C#中将字节数组转换为短数组 下载本文

内容发布更新时间 : 2024/6/16 12:55:24星期一 下面是文章的全部内容请认真阅读。

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

在 C#中将字节数组转换为短数组

2009/07/09 28406 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? 我该怎么做呢? 15

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); 49 Use Buffer.BlockCopy. 使用 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. 这是迄今为止最快的方法。 2

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)) 0

short[] wordArray = Array.ConvertAll(byteArray, (b) = (short)b); 0

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 没有提到他对短裤的使用或文件中短裤的定义。在他的情况下,将字节数 组转换为短数组是没有意义的,因为它需要两倍的内存,我怀疑在别处使用时是否 需要将一个字节转换为 short。 -2

byte[] bytes;var shorts = bytes.Select(n = System.Convert.ToInt16(n)).ToArray();tips:感 谢大家的阅读,本文由我司收集整编。仅供参阅!