Conversion from Hex to Decimal using Two Add-on

Asked

Viewed 88 times

2

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

It is a tracking system, according to the manual to 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 code above but I can’t get the same result.

1 answer

3


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);
      }
  }

Working:

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

    Single s = ConvertHexToSingle(valor);

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

Upshot: -22.85908

I put in the Dotnetfiddle

Source: https://www.codeproject.com/Questions/99483/Convert-value-by-IEEE-protocol

Browser other questions tagged

You are not signed in. Login or sign up in order to post.