orlp
orlp

Reputation: 117771

Fast bidirectional bitshift?

I have a piece of code that gets executed a lot, which I would like to optimize. It looks like this:

int exponent;
uint32_t mantissa;

if (exponent < 0) {
    return mantissa << -exponent;
} else {
    return mantissa >> exponent;
}

It's purpose is quite clear, it should right-shift mantissa by exponent places, where exponent can be negative.

Is there a faster way to code this (without the branch if possible)?

Upvotes: 2

Views: 205

Answers (2)

Anton Pegushin
Anton Pegushin

Reputation: 470

Take a look at this one "integer abs without branching". This guy has a great set of bit tricks including the one you want. Seems like in your case 'sizeof(int)*CHAR_BIT' should just be substituted with 8, if 'exponent' variable type never changes.

By the way, are you sure that this particular 'if'-statement is the performance problem due to branching? What I mean is that there's no point in optimizing away the branches if the problem lies with poor data locality somewhere else.

Upvotes: 0

leftaroundabout
leftaroundabout

Reputation: 120741

Sure there is. That is, a branch-free one; I wouldn't say it's necessarily faster in all circumstances.

int exponent;
uint32_t mantissa;

return (uint32_t)( (uint64_t)mantissa << (32-exponent) >> 32 );

Upvotes: 4

Related Questions