Hacker News new | ask | show | jobs
by shaggie76 22 days ago
While I'm a fan of unsigned (size_t mostly) there have been a few times when the tax for converting them to float was shockingly high:

https://godbolt.org/z/96T4jTshc

1-2 instructions for signed vs 11 including a branch for unsigned.

(in times like these I found casting to signed first preferable)

1 comments

That's a GCC skill issue. You can do it in five branchless instructions for unsigned by splitting the unsigned up in two 32-bit halves, converting those to floats simply by inserting their values as mantissa into constants 2^52 and 2^(52 + 32). This conversion is exact.

Then to finish the conversion you subtract 2^52 and 2^(52 + 32) respectively from the halves and add them together.

    vmovq       xmm0, rdi
    vpunpckldq  xmm0, xmm0, xmmword ptr [rip + .CONST1]
    vsubpd      xmm0, xmm0, xmmword ptr [rip + .CONST2]
    vshufpd     xmm1, xmm0, xmm0, 1
    vaddsd      xmm0, xmm1, xmm0
Here CONST1 = [0x43300000, 0x45300000, 0, 0] and CONST2 = [0, 0x43300000, 0, 0x45300000].