C# 如何将字节数组转换为 int 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11112216/
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
How to Convert a byte array into an int array?
提问by user1166981
How to Convert a byte array into an int array? I have a byte array holding 144 items and the ways I have tried are quite inefficient due to my inexperience. I am sorry if this has been answered before, but I couldn't find a good answer anywhere.
如何将字节数组转换为 int 数组?我有一个包含 144 个项目的字节数组,由于我的经验不足,我尝试的方法效率很低。如果之前已经回答过这个问题,我很抱歉,但我在任何地方都找不到好的答案。
采纳答案by vcsjones
Simple:
简单的:
//Where yourBytes is an initialized byte array.
int[] bytesAsInts = yourBytes.Select(x => (int)x).ToArray();
Make sure you include System.Linqwith a using declaration:
确保包含System.Linqusing 声明:
using System.Linq;
And if LINQ isn't your thing, you can use this instead:
如果 LINQ 不是你的东西,你可以用它来代替:
int[] bytesAsInts = Array.ConvertAll(yourBytes, c => (int)c);
回答by Kevin Struillou
I known this is an old post, but if you were looking in the first place to get an array of integers packed in a byte array (and it could be considering your array byte of 144 elements), this is a way to do it:
我知道这是一篇旧帖子,但是如果您首先要获取一个字节数组中的整数数组(并且可能会考虑您的 144 个元素的数组字节),这是一种方法:
var size = bytes.Count() / sizeof (int);
var ints = new int[size];
for (var index = 0; index < size; index++)
{
ints[index] = BitConverter.ToInt32(bytes, index * sizeof (int));
}
Note: take care of the endianness if needed. (And in most case it will)
注意:如果需要,请注意字节序。(并且在大多数情况下会)
回答by Dimuth Ruwantha
Now It's Simple like follows,
现在很简单,如下所示,
int[] result = Array.ConvertAll(bytesArray, Convert.ToInt32);

