Convert Byte array to Integer 2 bytes at a time

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Chintan Shah
    New Member
    • Jan 2011
    • 6

    Convert Byte array to Integer 2 bytes at a time

    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.
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    There are two ways you can do this:

    1) Using shifting and masking.

    2) Using the BitConverter: http://msdn.microsoft.com/en-us/library/bb384066.aspx

    In both cases, your numbers are in the wrong order so you'd have to prepare them. The first two bytes don't make 1, they actually make 256 in the order they appear. You'd need to reverse that order to get the correct number.

    If you're doing this with shifting, the result happens naturally. You can loop through the numbers (in steps of 2). Then you can OR (|) the number into a destination, shift it left by 8 (the size of a byte), then OR in the second number.

    If you're doing it with a bit converter, you'll need to copy the first byte into the second element of a new byte array and the second byte into the first element of that array, then run it through the bit converter.

    Comment

    Working...