Thursday, July 24, 2008

C# convert between int and byte array

BitConverter is a native way of converting int and byte[]. In fact, converting byte array into float(single in C#), double, Int16,Int32 etc....

For example:
int tmp = 10;
byte[] b = BitConverter.GetBytes(tmp);

// convert to float
byte[] b = new byte[4];
BitConverter.ToSingle(b, 0);

Depending on how you want the byte[] to be converted, BitConverter has whole lot functions to do that.Only to remember, if you are about to convert 8 bit byte array, you can simply cast it to int.

One interesting thing is that when you wanted to receive bytes from network, you might need to worry about big endian and little endian issue. I saw some hard solutions, but found a simple way of doing it.

byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
Array.Reverse(receiveBytes);

Enjoy

No comments: