How do I change data type float to hex?

Hi, I use nRF52840, with SDK 15.3.0

Using UART communication, stored data should be unsigned integer 16 bit.

And the data should be calculated to float data type.

To summarize, declare data type to unsigned integer, calculate to float type, change data type to unsigned integer.

Using UART communication, only declare data type to unsigned integer type.

Thanks in advance!

Parents
  • Hi 

    As you probably know a float data type in C is stored in 32 bits, so if you want to convert a float value to 16 bits you will need to accept some loss of precision. 

    What kind of numbers do you need to store? Will they not contain a fractional part, only integer values below 2^16 (to fit in a unsigned 16 bit integer) ?

    Best regards
    Torbjørn

  • Thank you for your quick reply.

    I'd like to store value 0.0~12.7 convert to unsigned integer 16-bit, and the value will be express to two size of uint16_t array.

    ex) uint16_t buffer[2] = {0x0000, 0x0000};

      buffer[0] = measure_value(converted to hex);

      buffer[1] = measure_value(converted to hex)<<16;

    Best regards

    William

  • Hi William

    In that case you should be able to copy the raw value of the upper and lower bytes of your float directly into your two uint16 variables. 

    A trick to do this is to get a pointer to your float, cast it to a uint16 pointer, and then dereference the pointer again to only access the lower and upper 16 bits. 

    Please try the following code:

    float measure_value;
    uint16_t buffer[2];
    buffer[0] = ((uint16_t*)&measure_value)[0];
    buffer[1] = ((uint16_t*)&measure_value)[1];

    Best regards
    Torbjørn

Reply
  • Hi William

    In that case you should be able to copy the raw value of the upper and lower bytes of your float directly into your two uint16 variables. 

    A trick to do this is to get a pointer to your float, cast it to a uint16 pointer, and then dereference the pointer again to only access the lower and upper 16 bits. 

    Please try the following code:

    float measure_value;
    uint16_t buffer[2];
    buffer[0] = ((uint16_t*)&measure_value)[0];
    buffer[1] = ((uint16_t*)&measure_value)[1];

    Best regards
    Torbjørn

Children
No Data
Related