Skip to main content
Visitor II
February 18, 2021
Question

how to join two bytes into a 16-bit float. .

  • February 18, 2021
  • 3 replies
  • 1847 views

the microcontroller receives a total of 4 bytes of data every 50 µs via SPI.  each Two bytes form a value,  which is represented as a float with 16 bits.

how can i join two bytes into a 16-bit float?

float v_beta_d_star = 0.0f;

float v_beta_q_star = 0.0f;

float v_beta_d_star = (spi_values[0] << 8) | (spi_values[0] & 0xFF);

float v_beta_d_star = (spi_values[1] << 8) | (spi_values[1] & 0xFF);

    This topic has been closed for replies.

    3 replies

    Graduate II
    February 18, 2021

    floats have 32 bit, and they dont store data the same way as integers or byte variables.

    I dont know if this will help you but:

    from two byte variables to one uint16_t;

    memcpy(&first16bitvariable,&spi_values[0],2);

    memcpy(&second16bitvariable,&spi_values[2],2);

    once you have the 16bit integers you can use them to do some maths with floats

    Graduate II
    February 18, 2021

    Nitpicking:

    memcpy does not care for byte order in your spi data. With 16bitvariable = spi_values[0] | spi_values[1] << 8 or 16bitvariable = spi_values[1] | spi_values[0] << 8 you can care for byte order.

    Explorer
    February 18, 2021

    Floating point formats are standardized, see here: https://en.wikipedia.org/wiki/IEEE_754

    For endianess, check the datasheet of the SPI slave you receive the values from.

    Alternatively, the datasheet should define the number format used.