Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert int[] to int[,] - C#

I have an int array in one dimension:

var intArray=new[] { 1, 2, 3, 4, 5, 6 };

and I want to convert it to two dimensions, such as:

var intArray2D=new[,] { {1, 2}, {3, 4}, {5, 6} };

How do I achieve this with C#?

like image 209
Syma Avatar asked Apr 24 '13 22:04

Syma


People also ask

Can we convert char to int in C?

There are 3 ways to convert the char to int in C language as follows: Using Typecasting. Using sscanf() Using atoi()

How do you convert an array of integers into a single integer in CPP?

Iterate the array and convert the values into string. Then concatenate all of them and convert back to integer. Save this answer.

Can we convert int to string in C?

Method 1 – Convert Int to String Using the Sprintf Function The Sprintf function is one of the functions you can use to convert an integer value into a string. As the name suggests, the function will take any value and print it into a string. It is very similar to the printf function.


2 Answers

with a loop perhaps:

for (int i = 0; i < oldArr.Length; i=i+2)
{
    newArr[i/2, 0] = oldArr[i];
    newArr[i/2, 1] = oldArr[i + 1];
}

Untested, but should get you pointed in the right direction...

like image 95
Abe Miessler Avatar answered Sep 19 '22 13:09

Abe Miessler


If the one dimensional array contains the primitive data in row major order, and the total capacity of the 2 dimensional array equals the length of the one dimensional array, you can use this.

int[] source = new int[6];
int[,] target = new int[3, 2];
Buffer.BlockCopy(source, 0, target, 0, source.Length * sizeof(int));

Note that unlike Array.Copy and other array/list methods, Buffer.BlockCopy operates on a number of bytes of data, even if each element of the array is larger than 1 byte. It also only operates on arrays of primitive data types.

Additional references:

  • Multi-dimensional arrays are stored in row-major order (ECMA-335 Partition I, §8.9.1)
  • Buffer.BlockCopy

Edit: Here is a complete unit test.

[TestMethod]
public void SOTest16203210()
{
    int[] source = new int[6] { 1, 2, 3, 4, 5, 6 };
    int[,] destination = new int[3, 2];
    Buffer.BlockCopy(source, 0, destination, 0, source.Length * sizeof(int));
    Assert.AreEqual(destination[0, 0], 1);
    Assert.AreEqual(destination[0, 1], 2);
    Assert.AreEqual(destination[1, 0], 3);
    Assert.AreEqual(destination[1, 1], 4);
    Assert.AreEqual(destination[2, 0], 5);
    Assert.AreEqual(destination[2, 1], 6);
}
like image 43
Sam Harwell Avatar answered Sep 22 '22 13:09

Sam Harwell