Circular Shifting with only three bits

Arokh

Centurion
Joined
Apr 11, 2006
Messages
124
Hi,
I'm in need of circular shifting, which isn't supported in VB.NET.
To make things a bit more complicated (no pun intended :p ),
I only want to use the first 3 bits to do the rotation. (Just imagine a 3 bit integer)

I've come up with some solutions,
but I hope there is a more elegant, maybe faster solution.

Shift to the right:
X = ((X >> 1) Or ((X Mod 2) << 2))

Shift to the left:
X = (X << 1 Or ( (8 And (X << 1) ) >> 3)) And 7

Note:
I only need to shift by one, never more.
 
I think that that is as simple as it is going to get. If you are going to do a bit rotation with a non-supported bit-size, you will always have to perform the carry yourself (i.e. the extra shift and 'or'). If you can safely operate under the assumption that only the least significant 3 bits are ever set, you can do away with some bit masking there.
 
Small improvement

For the shl, you can do away with one of those shifts, and for the shr, you can use And instead of Mod.

Visual Basic:
'Assuming only the 3 least significant bits are set
'Shift right
X = (X >> 1) Or ((X And 1) << 2)
'Shift left
X = ((X And 3) << 1) Or ((X And 4) >> 2)

I doubt it gets much simpler than that.

Good luck :cool:
 
Back
Top