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!

8
  • 2
    Does this answer your question? Convert Bytes to Floating Point Numbers? Commented May 20, 2021 at 8:20
  • Also relevant: How are floating point numbers stored in memory? Commented May 20, 2021 at 8: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*' Commented May 20, 2021 at 8:59
  • @doeppler mind the spaces I've added: b'\xea \xa6 \x9a @ \x04 *' - that's obviously 6 bytes. Commented May 20, 2021 at 9:01
  • @alagner It's too bad I can't mark your comment as an answer but you helped me. So, thank you! Commented May 20, 2021 at 9:35

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.