1

I would like to convert an array of bytes, received from serial, to a float.

Let's consider this exemple. I'm sending 0.12 byte-wise from an Android application. The conversion from float to array of bytes in the Android side is handled by this function

public static byte [] float2Bytes(float value)
 {
 return ByteBuffer.allocate(4)./*order(ByteOrder.LITTLE_ENDIAN).*/putFloat(value).array();
 }

When bytes arrive, they are stored in an array and the assembled.

hiBytew1 = bufferBytes[9];
//Serial.println(hiBytew1);
loBytew1 = bufferBytes[10];
//Serial.println(loBytew1);
hiBytew2 = bufferBytes[11];
//Serial.println(hiBytew2);
loBytew2 = bufferBytes[12];
//Serial.println(loBytew2);
float conAck = assemble(hiBytew1, loBytew1, hiBytew2,loBytew2);

How can I achieve this kind of conversion assuming that bytes are received in the correct order?

asked Jun 19, 2015 at 18:56

1 Answer 1

3

Just cast the pointer.

float conAck = *((float*)(bufferBytes + 9));
answered Jun 19, 2015 at 18:59
6
  • 1
    This needs parentheses around "bufferBytes + 9". Commented Jun 19, 2015 at 19:00
  • Right, otherwise it will advance sizeof(float) * 9 bytes instead. Commented Jun 19, 2015 at 19:01
  • Grazie Ignacio, so it will automatically assemble the sequence in a float variable? Nice Commented Jun 19, 2015 at 19:02
  • 2
    @UserK: It will tell the compiler that the bytes it will be looking at are a float. Commented Jun 19, 2015 at 19:02
  • @userk there is no assembly. Floats are already stored as bytes in memory. You are asking android to put the 4 most meaningful bytes in the buffer. Then you are trekking arduino to consider the bytes together as a float. If you are to store the same number in memory it week have the same representation. In a nutshell, this is an O(1) operation. Commented Jun 25, 2015 at 14:58

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.