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

2 comments:

simi said...

hi,

First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook

http://www.csharptalk.com/2009/09/c-array.html
http://www.csharptalk.com/2009/10/creating-arrays.html

simi

navya said...

Great Article
C# Training in Chennai | C# Online Training | ASP.NET Training in Chennai

C# Training in Chennai | Dot Net Training in Chennai | Dot Net Training in Chennai