is it possible to handle negative shift values without a branch? For example, a<<-1 should equal a>>1
Currently I use
- Code: Select all
if (a>b)
x>>=(a-b);
else
x<<=(b-a);
Can I get rid of the "if"?
Moderator: Andres Valverde
if (a>b)
x>>=(a-b);
else
x<<=(b-a);
Dann Corbit wrote:You did it the right way.
Onno Garms wrote:Dann Corbit wrote:You did it the right way.
Well, I'm right to use a workaround, because things like a<<-1 are undefined.
I'd like to know if it's possible to write a branchless workaround, i.e. well-defined code that leads to the same result like my workaround.
What about the assembler instructions for shift and rot? Are they also undefined?
Even if they are undefined, I might use one rotl, one rotr and one mask operation to implement x<<=(a-b) without a branch. But this looks compicated and might be even slower than the solution with a branch.
x = (a-b > 0) ? x >> (a-b) : x << -(a-b);
int diff = b-a;
int mask = diff >> 31; // 31 == 8*sizeof(int) - 1
x >>= -diff & mask;
x <<= diff & ~mask;
x >>= a;
x <<= b;
rjgibert wrote:Using a 32 bit word and limiting oneself to 16 bit values (x = 0 to 65535),
Return to Programming and Technical Discussions
Users browsing this forum: No registered users and 5 guests