Answer the question
In order to leave comments, you need to log in
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
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);
}
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.
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.
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question