user1166981
user1166981

Reputation: 1746

How to Convert a byte array into an int array?

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.

Upvotes: 27

Views: 49482

Answers (5)

wade.ec
wade.ec

Reputation: 311

Use Buffer.BlockCopy instead of Array.ConvertAll.

ref Converting an int[] to byte[] in C#

byte[] bytes = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 };
int[] ints = Array.ConvertAll(bytes, Convert.ToInt32);

will return ints[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}, not return ints[] = {0x04030201,0x08070605}

You should use Buffer.BlockCopy(bytes, 0, ints, 0, bytes.Length);

Upvotes: 11

user2791333
user2791333

Reputation: 31

What you really need is:

Span<int> integerArray = MemoryMarshal.Cast<byte, int>(byteArray.AsSpan());

source -> https://stackoverflow.com/a/56029829/2791333

Upvotes: 3

Dimuth Ruwantha
Dimuth Ruwantha

Reputation: 705

Now It's Simple like follows,

int[] result = Array.ConvertAll(bytesArray, Convert.ToInt32);

Upvotes: 9

Kevin Struillou
Kevin Struillou

Reputation: 914

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:

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)

Upvotes: 14

vcsjones
vcsjones

Reputation: 141588

Simple:

//Where yourBytes is an initialized byte array.
int[] bytesAsInts = yourBytes.Select(x => (int)x).ToArray();

Make sure you include System.Linq with a using declaration:

using System.Linq;

And if LINQ isn't your thing, you can use this instead:

int[] bytesAsInts = Array.ConvertAll(yourBytes, c => (int)c);

Upvotes: 37

Related Questions