converting an int array to a byte array

T

Tomas Deman

Hi,

I need a fast method for converting an int array to a byte array.
At the moment, I'm using this:
public static byte[] Int2ByteArray(int[] array)
{
byte[] lbytRetval = new byte[array.GetLength(0) * 2];
int lintIdxHi;
int lintIdxLo;
for (int i = 0; i < array.GetLength(0); i++)
{
lintIdxHi = (i * 2);
lintIdxLo = lintIdxHi + 1;
lbytRetval[lintIdxLo] = (byte)(array % 0xff);
lbytRetval[lintIdxHi] = (byte)((array - lbytRetval[lintIdxLo]) /
0xff);
}
return lbytRetval;
}

I was thinking of using Marshal.Copy but can't get it to work.
 
T

Tom Shelton

Hi,

I need a fast method for converting an int array to a byte array.
At the moment, I'm using this:
public static byte[] Int2ByteArray(int[] array)
{
byte[] lbytRetval = new byte[array.GetLength(0) * 2];
int lintIdxHi;
int lintIdxLo;
for (int i = 0; i < array.GetLength(0); i++)
{
lintIdxHi = (i * 2);
lintIdxLo = lintIdxHi + 1;
lbytRetval[lintIdxLo] = (byte)(array % 0xff);
lbytRetval[lintIdxHi] = (byte)((array - lbytRetval[lintIdxLo]) /
0xff);
}
return lbytRetval;
}

I was thinking of using Marshal.Copy but can't get it to work.


Have you looked at the System.BitConverter.GetBytes method?
 
M

Mattias Sjögren

Tomas,

Buffer.BlockCopy would be the easiest way to do that. But note that an
int is four bytes, not just two that you're assuming now. So the byte
array you copy the data to would have to be four times the length of
the int array.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top