I recently needed to convert an array of integers to an array of bytes in order to work with an existing database design. I looked online and couldn’t find a function to convert between the two types so I wrote my own.
Convert int[] to byte[]:
public static byte[] GetByteArrayFromIntArray(int[] intArray)
{
byte[] data = new byte[intArray.Length * 4];
for (int i = 0; i < intArray.Length; i++)
Array.Copy(BitConverter.GetBytes(intArray[i]), 0, data, i * 4, 4);
return data;
}
Convert back to int[]:
public static int[] GetIntArrayFromByteArray(byte[] byteArray)
{
int[] intArray = new int[byteArray.Length / 4];
for (int i = 0; i < byteArray.Length; i += 4)
intArray[i / 4] = BitConverter.ToInt32(byteArray, i);
return intArray;
}
*Notice BitConverter.GetBytes will always return a 4 byte array.
Hope you find this usefull.
Posted
26 May 2010 6:20 AM
by
Gal Ratner