converting an int array to a byte array

  • Thread starter Thread starter Tomas Deman
  • Start date Start date
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.
 
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?
 
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
 
Back
Top