Click here to Skip to main content
15,903,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a byte array which looks something like

01 00 02 00 73 45 69 A5

So i have to read first 2 bytes and convert it into integer to get its value.
Same for next 2 bytes and then next 4 bytes.

Here the value for first 2 bytes (01 00) is 1, next 2 bytes (02 00) is 2.

So could some one help me on this.
Dave Kreskowiak 12-Jan-11 9:33am    
Are you saying that you have to reverse the order of the 2 bytes, then get it's value?? Because 0x0100 is 256 decimal, not 1. 0x0200 is 512 decimal, not 2.

The framework has a class to convert byte array to primitive types and vice versa.

The System.BitConverter[^] class is worth a passing glance as it's very useful and the ToInt16 method is the solution to your problem.

Share this answer
Estys 12-Jan-11 10:18am    
Cool! have 5
I assume unsigned numbers.

byte[] b

int i = b[x] + b[x + 1] * 256

Throw a loop with an increment of 2 of x around it.

Share this answer
DaveyM69 12-Jan-11 13:59pm    
I would prefer << 8 to * 256 as it represents what is happening better - just a preference!
fjdiewornncalwe 12-Jan-11 14:38pm    
I agree with DaveyM69. Show that you are bitshifting as the multiply method is a little ambiguous as to what is happening, but you still get a +5 for the solution.
Anyway, converting two bytes to an integer is very easy. Take the first byte (as an integer), multiply it by 256 and add the second byte.
Share this answer
fjdiewornncalwe 12-Jan-11 14:39pm    
+5 from me.
//for next bytes you just need to increament startIndex by 2

byte [] bytes;

System.BitConverter.ToInt16( bytes , startIndex);
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900