Search code examples
carrayspointersvariables

How can I store float variable to int array (C)?


Is there a way to store float variable for example: PI (3.1415) to int16_t array, and then print it using pointers?


Solution

  • This is how you can do it w/ pointer casting:

    float f = 3.14; // float -> 4 bytes
    int16_t i[2];   // int16_t -> 2 x 2 bytes each
    
    i[0] = *(((int16_t *)&f) + 0);
    // store first 2 bytes of float into i[0]
    // be careful here!!! endianness matters
    // for little endian, use
    // i[0] = *(((int16_t *)&f) + 1);
    
    i[1] = *(((int16_t *)&f) + 1);
    // store last 2 bytes of float into i[1]
    // be careful here!!! endianness matters
    // for little endian, use
    // i[1] = *(((int16_t *)&f) + 0);
    
    printf("%d\n", (int)i[0]);
    // prints the int16_t representation 
    // of the first 2 bytes of float bit pattern
    printf("%d\n", (int)i[1]);
    // prints the int16_t representation 
    // of the last 2 bytes of float bit pattern
    
    printf("%f\n", *((float *)&i));
    // prints the float in full