Byte array to integer

Convert 2 bytes of byte array to integer at a time

Page 1 of 1

2 Replies - 5256 Views - Last Post: 12 January 2011 - 07:53 AM Rate Topic: -----

#1 chintan_1671   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 22-December 08

Byte array to integer

Posted 12 January 2011 - 07:12 AM

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.

This post has been edited by chintan_1671: 12 January 2011 - 07:25 AM

Is This A Good Question/Topic? 0
  • +

Replies To: Byte array to integer

#2 lordofduct   User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2668
  • View blog
  • Posts: 4,786
  • Joined: 24-September 10

Re: Byte array to integer

Posted 12 January 2011 - 07:42 AM

well I don't know about your order... it seems the bytes are being combined left to right (hence how [01, 00] becomes 0001). And I don't know about the clusters (why 2,2,4... are there move values? Are these the only values?) So really the only thing we have enough info to assist you with is to show you how to combine bytes into an Integer.

In this quick example I'm going to write a method that returns an integer for 4 bytes. Why 4? Because an integer is 32-bits, which is 4*8, or 4 bytes.

        public int ToInt(byte arg0, byte arg1, byte arg2, byte arg3)
        {
            return arg0 + (arg1 << 8) + (arg2 << 16) + (arg3 << 24);
        }



If you're only going to pass 2 bytes, then pass 0's for arg2 and arg3 (or you can write shorter overloads).

All I basically do is move each byte over the number of bits to put it in its relative position to the other bytes, and sum them. Notice they are multiples of 8 (8 bits being the number of bits in a byte).
Was This Post Helpful? 2
  • +
  • -

#3 chintan_1671   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 46
  • Joined: 22-December 08

Re: Byte array to integer

Posted 12 January 2011 - 07:53 AM

It worked ..
The 2 2 are for version and algoid and last 4 are crc taken from a file ..

Thanks
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1