Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operation on a floating point usefulness

I noticed a SSE instruction existed for floating point AND which got me wondering. You can do the same thing with scalars in fp/integer union.

The idea struck me that, if you bitwise OR the components of an array of floats, you can determine if any of them are negative quickly by looking at the sign bit of the result.

What other uses exist for bitwise operations on floating point values?

like image 403
Thomas Avatar asked Jan 08 '23 16:01

Thomas


1 Answers

A lot. For example when you only need to do bitwise operations on a floating-point only instruction set like AVX, then those become very handy.

Another application: making constants. You can see a lot of examples in table 13.10 and 13.11 in Agner Fog's optimization guide for x86 platforms. Some examples:

pcmpeqd xmm0, xmm0
psrld   xmm0, 30   ; 3 (32-bit)

pcmpeqd xmm0, xmm0 ; -1

pcmpeqw xmm0, xmm0 ; 1.5f
pslld   xmm0, 24
psrld   xmm0, 2

pcmpeqw xmm0, xmm0 ; -2.0f
pslld   xmm0, 30

You can also use that for checking if the floating-point value is a power of 2 or not.

Some other applications like Harold said: Taking absolute value and minus absolute value, copy sign, muxing... I'll demonstrate in a single data for easier understanding

// Absolute:
abs = x & ~(1U << 31);
// Muxing
v = (x & mask) | (y & ~mask); // v = mask ? x : y; with mask = 0 or -1
// Copy sign
y = (y & ~(1U << 31)) | (x & (1U << 31));
like image 187
phuclv Avatar answered Jan 17 '23 16:01

phuclv