converting a 2 bytes hexadecimal value to an integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mayaanu
    New Member
    • May 2010
    • 3

    converting a 2 bytes hexadecimal value to an integer

    Hai
    I am writing an application that reads the data from the serial port in to a byte array(example bf).I had converted the byte array to string using
    string s=Bitconverter. Tostring(bf)
    Now i want to get an integer value from 0th and 1st bytes in bytearray.
    the values that comes in my bytearray are
    bf[0]=165
    bf[1]=03
    when it is converted to string it will be A503
    i need an integer from bf[0] and bf[1].
    please help me
    thanks in advance
    maya
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    Look at the BitConverter class. It looks like it needs a byte array where the LSB is in the first index. So in your case, if you're looking to get A503, you'll want to have 03 in index 0 and 165 in index 1.

    Code:
                byte[] arr = new byte[] { 03, 165 };
                ushort v = BitConverter.ToUInt16(arr, 0);
    
                Console.WriteLine("Value: " + v.ToString());
                Console.WriteLine("Value (Hex): " + v.ToString("X"));
    Learn how to convert a byte array to an int. See code examples and view additional available resources.

    Comment

    Working...