简体   繁体   中英

How to convert hex to float using C#

I'm get data from ST MCU via UART and display value to PC screen but its result is different with what I expected in float type.

I'm using TrueStudio for ST MCU and C# to display values in screen. I'm using float value at MCU and send data to PC When I get in PC, if I display float value to textBox, its result is too different with I expected. In TrueStudio memory view and watch view, I can see below

  1. In TrueStudio MCU, I can see

    • in watch window : acc.x = 5.12400007
    • in memory view : 5.124000E0 in floating point format CFF7A340 in hex format
  2. I could get this data in PC via visual studio in C#

    • I can see byte[] array data via watch window and I can see I got

       msg[4] = 0xCF, msg[5] = 0xF7, msg[6] = 0xA3, msg[7] = 0x40 
    • so in dec, 3489112896
    • I converted this value with these but I couldn't get what I wanted, 5.124

       str = "3489112896" Convert.ToDouble(str) = 2246812992 

      Converted dec to UInt32 so

       u32 = Convert.ToDouble(str) u32 = 0xcff7a340 (double)u32 = 3489112896 (float)u32 = 3.48911283E+09 BitConverter.ToSingle(BitConverter.GetBytes((int)u32), 0) = -2.21599971E-35 

    In TrueStudio, copied like below (in C)

     memcpy(&ethBuf[len], &g_Bsp.acc, sizeof(ACC_ST)); len += sizeof(ACC_ST); 

    In visual studio, C#

     UInt32 u32 = (UInt32)( msg[4] | (msg[5] << 8) | (msg[6] << 16) | (msg[7]<<24)); LOG("u32 : " + u32 + "\\n"); 

    I have tried with MSB/LSB first and couldn't get what I wanted. How can I get 5.123 floating value in C#?

You can convert to hex using BitConverter.GetBytes and BitConverter.ToString :

public static string FloatToHex(float val)
{
    var bytes = BitConverter.GetBytes(val);
    return BitConverter.ToString(bytes).Replace("-", string.Empty);
}

And you can convert back from hex by converting the data back into a byte array, and then using BitConverter.ToSingle :

public static float HexToFloat(string hexVal)
{
    byte[] data = new byte[hexVal.Length / 2];
    for (int i = 0; i < data.Length; ++i)
    {
        data[i] = Convert.ToByte(hexVal.Substring(i * 2, 2), 16);
    }
    return BitConverter.ToSingle(data, 0);
}

Try it online

Depending on the system you want to exchange data with, you might have to account for endianness and reverse the order of the bytes accordingly. You can check for endianness using BitConverter.IsLittleEndian .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM