Fredou
Fredou

Reputation: 20140

Is there a better way to do a 4 bits circular shifting?

is this the optimal way of doing a 4 bits circular shifting?

    n << 1 ^ 0x10 | n >> 3

I was only testing with number that was actually "working"!

Upvotes: 0

Views: 113

Answers (3)

Hans Passant
Hans Passant

Reputation: 942099

Did you actually try this? It is non-optimal, it generates garbage results. This ought to work better:

    static int RollLeft4Bits(int n) {
        return ((n << 1) & 15) | ((n >> 3) & 1);
    }

Upvotes: 2

StarPacker
StarPacker

Reputation: 539

You could also generate a lookup table of every possible value and the shifted result. Then just use the input as an index into the lookup table to get the desired result

Upvotes: 1

David M
David M

Reputation: 72920

Looks pretty good to me. But if you are really that concerned about optimisation, then try compiling this and any alternatives you have, and then using ildasm or Reflector to look at the IL generated to see for sure.

Upvotes: 1

Related Questions