views:

120

answers:

5
  1. List item

How to convert an int[,] to byte[] in C#? Some code will be appreciated

EDIT:

I need a function to perform the following:

byte[] FuncName (int[,] Input)
+7  A: 

Like this, right?

byte[] FuncName (int[,] Input)
{
    return new byte[] { 4, 6, 8 }; // my favorite bytes
} 

(Or did you maybe want it to convert it in a particular way?)

mquander
You probably mean `new byte[] { 42 }` ;)
Thomas Levesque
Ah, that can't be, the poster wouldn't want a byte *array* unless he had *multiple* bytes in mind.
mquander
I'm thinking you missed the joke.
DarkBobG
+3  A: 

It seem that you are writing the types wrong, but here is what you might be looking for:

byte[] FuncName (int[,] input)
{
    byte[] byteArray = new byte[input.Length];

    int idx = 0;
    foreach (int v in input) {
        byteArray[idx++] = (byte)v;
    }

    return byteArray;
}
Martin Ingvar Kofoed Jensen
I'd give your guess "most likely to be his goal".
Scott Stafford
Mine is faster!
mquander
@mquander true, but mine seems to fit his needs.
Martin Ingvar Kofoed Jensen
+2  A: 

Since there is very little detail in your question, I can only guess what you're trying to do... Assuming you want to "flatten" a 2D array of ints into a 1D array of bytes, you can do something like that :

byte[] Flatten(int[,] input)
{
    return input.Cast<int>().Select(i => (byte)i).ToArray();
}

Note the call to Cast : that's because multidimensional arrays implement IEnumerable but not IEnumerable<T>

Thomas Levesque
+1  A: 

The BitConverter converts primitive types to byte arrays:

byte[] myByteArray = System.BitConverter.GetBytes(myInt);

You appear to want a 2 dimensional array of ints to be converted to bytes. Combine the BitConverter with the requisite loop construct (e.g foreach) and whatever logic you want to combine the array dimensions.

Ben Aston
+2  A: 

Here's an implementation that assumes you are attempting serialization; no idea if this is what you want, though; it prefixes the dimensions, then each cell using basic encoding:

public byte[] Encode(int[,] input)
{
    int d0 = input.GetLength(0), d1 = input.GetLength(1);
    byte[] raw = new byte[((d0 * d1) + 2) * 4];
    Buffer.BlockCopy(BitConverter.GetBytes(d0), 0, raw, 0, 4);
    Buffer.BlockCopy(BitConverter.GetBytes(d1), 0, raw, 4, 4);
    int offset = 8;
    for(int i0 = 0 ; i0 < d0 ; i0++)
        for (int i1 = 0; i1 < d1; i1++)
        {
            Buffer.BlockCopy(BitConverter.GetBytes(input[i0,i1]), 0,
                  raw, offset, 4);
            offset += 4;
        }
    return raw;
}
Marc Gravell