Bitwise operation on a floating point usefulness

我与影子孤独终老i 提交于 2020-01-02 06:33:12

问题


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?


回答1:


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));



回答2:


It can be used to extend the precision of floating point using so-called "double double" arithmetic, particularly when you don't have access to a fused-multiply add (FMA) instruction.

If you have two floats in which the last half of the significand is zero, then their product is exact. So a common trick is to zero out part of the float, subtract that from the original number, and you have two numbers which sum to the original value, but each use only half the significand. By appropriately arranging the order of operations, you can get two floats which sum to the exact product: see, for example, Dekker (1971).

I did some rough speed tests here using Julia: the floating point AND is at least 50% faster than shifting to the integer register, using integer AND, and shifting back.



来源:https://stackoverflow.com/questions/29195566/bitwise-operation-on-a-floating-point-usefulness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!