0

I am trying to send float values over UART to a PC and reconstruct these float values from their respective char array. How I am transferring the 32-bit float value to char is below:

  float value = 42.83f;
  unsigned char *ptr = &value;

And in the Python script received value is:

[236, 81, 43, 66, 4, 42]

How can I cast this char array back to 42.83f?

Thank you!

emirgo
  • 15
  • 5
  • 2
    Does this answer your question? [Convert Bytes to Floating Point Numbers?](https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers) – alagner May 20 '21 at 08:20
  • Also relevant: [How are floating point numbers stored in memory?](https://stackoverflow.com/questions/7644699/how-are-floating-point-numbers-stored-in-memory) – J_S May 20 '21 at 08:32
  • @alagner it kind of helps, however, I get the error "unpack requires a buffer of 4 bytes" this is my buffer at the moment and it seems fine to me: b'\xea\xa6\x9a@\x04*' – emirgo May 20 '21 at 08:59
  • @doeppler mind the spaces I've added: b'\xea \xa6 \x9a @ \x04 *' - that's obviously 6 bytes. – alagner May 20 '21 at 09:01
  • @alagner It's too bad I can't mark your comment as an answer but you helped me. So, thank you! – emirgo May 20 '21 at 09:35
  • @doeppler you're welcome ;) I wonder though how you're serializing and sending the data so you receive too much, but that's a topic for another question. – alagner May 20 '21 at 10:04
  • @alagner I use the ST-HAL from STM. The snippet of the code is below. I am always up for more learning :) float value[3] = {1.23, 2.23, 5.13}; unsigned char *ptr = &value; HAL_UART_Transmit(&huart2, ptr, strlen(ptr), 100); – emirgo May 20 '21 at 10:31
  • @doeppler you might want to read that: [Converting float to char*](https://stackoverflow.com/questions/2988791/converting-float-to-char). – alagner May 20 '21 at 11:01

1 Answers1

0

The way I decoded may be strange perhaps but I was receiving two elements more than needed for a float decode. Currently this is my shortcut solution: I pop the last two elements from the list meaning that I have 4 bytes left instead of 6 bytes. Then I use the following code to reconstruct the float value.

print("Processing...")
# process the data block
result_data.pop()
result_data.pop()
bytes_of_result = bytes(result_data)
print(bytes_of_result)
final_value = struct.unpack('f', bytes_of_result)
print(final_value)
emirgo
  • 15
  • 5