PROWAREtech

articles » current » dot-net » convert-int-array-to-bytes

.NET: Convert Int Array to Byte Array

How to use the BitConverter class to convert an array of integers (int) to an array of bytes and back again; written in C#.

In C#, convert an array of ints to an array of bytes and back again using the BitConverter class, which provides methods for converting base data types to an array of bytes and vice versa. Here’s how to do it:

1. Converting an Array of Ints to an Array of Bytes

To convert an array of ints to an array of bytes, iterate over the int array and convert each int to bytes. Since each int in C# is typically 4 bytes (32 bits), allocate an appropriate number of bytes to hold the converted values.


int[] intArray = new int[] { 1, 2, 3 };

byte[] byteArray = new byte[intArray.Length * sizeof(int)];

// NOTE: sizeof(int) is typically 4 (bytes)
for (int i = 0; i < intArray.Length; i++)
{
    BitConverter.GetBytes(intArray[i]).CopyTo(byteArray, i * sizeof(int));
}

2. Converting an Array of Bytes Back to an Array of Ints

To convert the byte array back to a int array, read every 4 bytes from the byte array and convert them back into ints.

 
int[] convertedIntArray = new int[byteArray.Length / sizeof(int)];

for (int i = 0; i < convertedIntArray.Length; i++)
{
    convertedIntArray[i] = BitConverter.ToInt32(byteArray, i * sizeof(int));
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE