displayName
displayName

Reputation: 14369

Bit-wise hack for updating a value when it is 0

Going through some legacy C++ code. At a lot of places I see the pattern:

if (theFloatValue == 0) theFloatValue = anotherFloatArray[4];

Is there a bit manipulation hack that can help me write a branchless code for the same?

The code in itself is fine and works without any issue.


Not trying premature optimization. Only asking out of curiosity after seeing the ubiquity of this code pattern.

Upvotes: 1

Views: 161

Answers (2)

Daniel Trugman
Daniel Trugman

Reputation: 8491

You can accomplish that using some math:

x is the value you want to manipulate, y is the value you want x to be when its 0.

Case #1

x = 0
=> !x = 1
=> !x * y = y
=> (!x * y) + x = (!x * y) = y

Case #2

x != 0
=> !x = 0
=> !x * y = 0
=> (!x * y) + x = 0 + x = x

Result

x = (!x * y) + x is what you need

Upvotes: 2

alain
alain

Reputation: 12037

If you can replace theFloatValue by an array, the following should[1] be branchless:

float theFloatValue[2];  // index 0: the old value, index 1: dummy
...
theFloatValue[theFloatValue[0] != 0] = anotherFloatArray[4]; // see [2]

theFloatValue[0] is now the former theFloatValue. The index 1 is used as an alternative location to place the result when it is not needed.

As always: This has to be tested if it makes an improvement or not.


[1] It's probably not branchless as Matteo Italia commented.

[2] With a NaN value, the calculation of the index theFloatValue[0] != 0 does not behave the same as the original from the question, as chris commented. With !(theFloatValue[0] == 0), this can be avoided, because the equality check on the float is the same. The 'not' is perfored on the bool.

Upvotes: 2

Related Questions