Conversion from Hex to Decimal using Complement of Two

3

I need to convert a string HEX to decimal , string uses the default Complement of Two and IEEE-754 to set the number of decimal places

It is a tracking system, according to the manual a string C1B6DF66 corresponds to -22,8590813 and C23C1762 corresponds to -47,0228348 .

var fb = Convert.ToUInt32(hx,16);
var twosComp2 = (~fb + 1);
var y= BitConverter.ToSingle(BitConverter.GetBytes((int)twosComp2), 0);

I'm using the above code but I can not get the same result.

    
asked by anonymous 09.03.2018 / 01:08

1 answer

4

I found the solution:

public static Single ConvertHexToSingle (string hexVal) 
{
      try 
      {
          int i=0, j=0;
          byte[] bArray = new byte[4];
          for (i = 0; i <= hexVal.Length-1; i += 2) 
          {
              bArray[j] = Byte.Parse (hexVal[i].ToString() + hexVal[i + 1].ToString(), System.Globalization.NumberStyles.HexNumber);
              j += 1;
          }
          Array.Reverse (bArray);
          Single s =  BitConverter.ToSingle (bArray, 0);
          return (s);
      } 
      catch (Exception ex) {
          throw new FormatException ("The supplied hex value is either empty or in an incorrect format.  Use the " +
              "following format: 00000000", ex);
      }
  }

Running:

public static void Main()
{
    string valor = "C1B6DF66";

    Single s = ConvertHexToSingle(valor);

    Console.WriteLine(s.ToString());
}
  

Result: -22.85908

I put it in DotNetFiddle

Source: link

    
09.03.2018 / 02:27