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
In TrueStudio MCU, I can see
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
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(ðBuf[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);
}
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
.