bitbonk
bitbonk

Reputation: 49659

Convert List<int> to byte[]

In .NET 2.0 is there an API that lets me quickly convert a list of integers to a byte array (List<int> to byte[])? The resulting byte array should be the bitwise binary representation of the sequence of integer values, so serailizing the the List instance using default .NET type serialization wouldn't work.

Upvotes: 0

Views: 3211

Answers (1)

thecoop
thecoop

Reputation: 46168

List<int> intList = new List<int>();
int[] intArray = intList.ToArray();
byte[] byteArray = new byte[intArray.Length*4];
Buffer.BlockCopy(intArray, 0, byteArray, 0, byteArray.Length);

Buffer.BlockCopy uses raw memory addresses, not array indexes, to copy array data. It only works on arrays of primitives.

Upvotes: 3

Related Questions