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.

Edited by chintan_1671: n/a

3
Contributors
4
Replies
6
Views
7 Years
Discussion Span
Last Post by ddanbe

Byte swapping and reading two bytes at a time and convert to integer are linked ?

You need to swap bytes.
You can find info on that here: http://msdn.microsoft.com/en-us/library/aa288465(v=vs.71).aspx

I didn't get the connection either. In your case you need to build the value byte by byte, which initially suggests bitwise operations, but there's a BitConverter class that will do what you want (unless you want something strange):

``````using System;

namespace Project1 {
class Program {
public static void Main()
{
Console.WriteLine(BitConverter.ToInt16(new byte[] { 0x01, 0x00 }, 0));
Console.WriteLine(BitConverter.ToInt16(new byte[] { 0x02, 0x00 }, 0));
Console.WriteLine(BitConverter.ToInt32(new byte[] { 0x73, 0x45, 0x69, 0xA }, 0));
}
}
}``````

So you want to read 2 bytes out of a file and convert them to an integer value, right?
If you say your first 2 bytes are 01 00 and you want them to be an integer with the value of 1. You have to swap the bytes like this 00 01.
This can be interpreted as 1, if read. The value in the file would be read as 4.
Because a byte is 8 bits long, this is of course an int16 type.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.