A
A
askogorev2013-12-05 22:46:50
C++ / C#
askogorev, 2013-12-05 22:46:50

Bit operation in C++ (n < max_n, then n; n == max_n, then 0;)

Good evening, is it possible to implement the following using bitwise operations?
There are n and max_n. Is it possible to somehow impose a mask or something, so that when:
n < max_n, then n;
n >= max_n, then 0;

Answer the question

In order to leave comments, you need to log in

5 answer(s)
J
jcmvbkbc, 2013-12-06
@jcmvbkbc

For example like this (I took the fixed width type for simplicity):

int32_t cap(int32_t n, int32_t max_n)
{
    return n & ((n - max_n) >> 31);
}

T
Teivaz, 2013-12-06
@Teivaz

If you do this to speed up the condition check, then it makes sense when n_max is a power of two.
then the maximum value will look, for example, like this:
Any number that is greater than n_max will have one in one of the most significant digits.
Then when applying a mask:
we will get either zero (when the number is less than the maximum), or some value (when the number is greater than or equal to).
But this does not make much sense, since the comparison will be compiled into two operations (except for the transfer of values ​​from register to register) in a clock cycle each: subtracting the current value from the maximum value and checking the negative flag of the subtraction result.

X
xanep, 2013-12-06
@xanep

If it's for academic purposes, then jcmvbkbc answered.
But in a real application, this should never be done. Current compilers do optimization well, even if you win one instruction, it won't make your application faster. But unreadability will add hoo how.

T
Trrrrr, 2013-12-10
@Trrrrr

The main idea is simple:
let it be

if (a < b) 
{
x = f(1); 
}
else
{
x = f(2);
}

это можно заменить так:
f1 = f(1);
f2 = f(2);
mask = (a < b) * 0xFFFFFFFF;/// это просто упрощенный пример, что бы вернуть или 0 или 0xFFFFFFFF

//тогда 
x = (mask & f1) | (~mask & f2);

If f1 and f2 are computed quickly, then we benefit from the processor's pipelined architecture. Since the conditional transition disappears from us. But if f is a heavy function, then it will probably be much faster to check the if and calculate only one of the options.
True, most often this was done when working with SSE2.

S
Sergey, 2013-12-05
Protko @Fesor

one question... why? this is solved by the ternary operator, and no perversions ... or functions like max / min.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question