Simplified version return ((union {float v; uint32_t r;}) {(int) x} .r >> 21) - 496

I found some code in the implementation of malloc.c, can someone please tell me what this code actually does:

return ((union { float v; uint32_t r; }){(int)x}.r>>21) - 496

I did some searching and found that it converts an integer to an IEEE 754 floating point, but I cannot figure out how this works. Can someone help me in understanding this in a few steps?

+4
source share
2 answers

This part is a composite literal :

(union { float v; uint32_t r; }){(int)x}

This is basically a conversion from a variable cast in intto float(the first element union)

Uses this floatas uint32_t:

.r

And removes the last 21 bits (mantissa?):

>>21

-496

:

union t {
   float v;
   uint32_t r;
};

union t u;

u.v = (int)x;
u.r >>= 21;
return u.r - 496; 
+2

4 * log 2 x + 12 - .

, float .

:

#include <stdio.h>
#include <stdint.h>
#include <math.h>

int makesize(uint32_t x) {
    return ((union { float v; uint32_t r; }){(int)x}.r>>21) - 496;
}

int main(void) {
    for (uint32_t i = 1 ; i != 1000 ; i++) {
        double v = i;
        double x = log(v)/log(2);
        int y = makesize(i);
        int res= 12+((int)floor(4*x));
        printf("%04d : %d,%d (%d)\n", i, y, res, y-res);
    }
    return 0;
}

-

1 999 , 1 .

+3

Source: https://habr.com/ru/post/1655106/


All Articles