Search code examples
cfloating-pointtype-conversionuint8t

Convert float to uint8 buffer


A have a float variable, and I need it's value to be stored in a uint8 buffer as characters. To be more exact, given something like this

float f = 123.45
uint8_t buffer[11];
memset(buffer, 0x30, sizeof(buffer));   // I set it at 0x30 because it is character '0' 

Given this example, my buffer needs to get the values:

0x30 0x30 0x30 0x30 0x30 0x31 0x32 0x33 0x2E 0x34 0x35   // 0x2E is the character '.'

I unfortunately need it this way to integrate it with a existing functionality, so there is no way around the size 11 buffer.

Any suggestion on how to go about this would be appreciated.


Solution

  • An easy way is:

    1. Allocate buffer with one more element (buffer_buffer here)
    2. Convert the float to string via snprintf()
    3. Copy the conversion result to buffer
    #include <stdio.h>
    #include <string.h>
    #include <inttypes.h>
    
    int main(void) {
        float f = 123.45;
        uint8_t buffer[11];
        char buffer_buffer[12];
        snprintf(buffer_buffer, sizeof(buffer_buffer), "%011.2f", f);
        memcpy(buffer, buffer_buffer, sizeof(buffer));
        for (int i = 0; i < 11; i++) printf(" 0x%02X", buffer[i]);
        putchar('\n');
        return 0;
    }
    

    Directly using snprintf() to buffer won't work well because there are no room for terminating null-character there.