15,903,175 members
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.
Posted
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.

## Solution 4

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.

Alan.

Estys 12-Jan-11 10:18am
Cool! have 5

## Solution 2

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.

Cheers

v2
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.

## Solution 1

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.

fjdiewornncalwe 12-Jan-11 14:39pm
+5 from me.

## Solution 5

//for next bytes you just need to increament startIndex by 2

byte [] bytes;

System.BitConverter.ToInt16( bytes , startIndex);

v2