Float to bytes array and back

hello, how can I convert byte array in to a float and back
For exapmle i have
float f=1.5;
to send it by Serial i wanna conwert it into a byte[4] array.
And back, by receiving byte[4] array — convert into a float.Текст "как есть" (без применения форматирования)

Describe the byte array, and explain the operation you have in mind.

A float value is stored in memory as an array of four bytes.

Look into using a ‘union’.

Do you want to convert each byte or do you want to cast 4 bytes to floating point value;
unsigned char ar[8];
// ... fill in ar from communication link
float f=ar[0]; // convert
float f=(float) &ar[0]; // cast == I typed (star) (float (star)) & // but the new forum removed the star symbol??
float f1=(float) &ar[4]; // cast == I typed (star) (float (star)) & // but the new forum removed the star symbol??
And I formatted as code like we used to do?

Im sorry its my first expirience of c++ coding, do u mean this function, that can return me float by array of 4 bytes?
float byteToFloat(byte bytesAsFloat[4]){ return *(float*) &bytesAsFloat[4]; }

Serial.write ((uint8_t *) &f,4);

1 Like
union Test
{
   unsigned long longNumber; //or float
   byte longBytes[4];
};
Test num;
. . .
num. longNumber = 0x12345678;
Serial.println( num.longBytes[0], HEX);
1 Like

Discourse supports the Markdown markup language. In Markdown, a single * adjacent to text is the syntax for italics:
https://www.markdownguide.org/basic-syntax/#italic
So instead of *, you got italicized text.

Unfortunately, this forum works differently in terms of creating code blocks. In the old SMF forum, we could click the </> button and then paste the code. But in this new Discourse-based forum you must do this:

  1. Paste the code into the post composition field
  2. Select the code you want to put in a code block.
  3. Click the </> button.

You will now find that all the code has been indented by four spaces. This is the Markdown syntax for a code block:
https://www.markdownguide.org/basic-syntax/#code-blocks

Experienced users might actually find it easier to just manually add the markup for code blocks. You can use the old style BBCode if you prefer

[code]
void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}
[/code]

Or it's even faster to do it using Markdown fenced code blocks:
https://www.markdownguide.org/extended-syntax/#fenced-code-blocks
Just add three backticks (```) on the line before and after the code:

```
void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}
```

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.