0

I have a number in bitwise form (eg 10101111000010...), 30 digits long. Let it be

abcdefgh.....wxyz

I want a slick way to shift it around, so it stays 30 digits, but it is shifted 3, but the top three are then put at the bottom.

defgh.....wxyzabc

So everything is shifted up 3, but the top three digits are put on the right.

How can this be done neatly.

Also I need the reverse operation, so if I start with

abcdefgh....wxyz

It shifts the other way

xyzabcdefgh....w

This is all done in the 30 digit area. All bits outside the 30 digit area remain 0.

This all has to be done with one eye on the fact that javascript only credibly recognises numbers up to 52/53 bits.

What I have so far but it looks yuck:

var digits = 30;
var shift = 3;
var value = 167596277;
var shiftedValue = (value >> shift) | (value & (Math.pow(2, shift)-1)) << (digits - shift);
Rewind
  • 2,554
  • 3
  • 30
  • 56
  • You are trying to create a "Barrel/Circular Shifter" depending on the language this may be a duplicate *C++: * http://stackoverflow.com/questions/25799215/bitwise-rotation-circular-shift and another http://stackoverflow.com/questions/776508/best-practices-for-circular-shift-rotate-operations-in-c *java* http://stackoverflow.com/questions/5844084/java-circular-shift-using-bitwise-operations *javascript* http://codereview.stackexchange.com/questions/41006/rotating-array-members – andrew Sep 26 '16 at 22:07
  • This is called "rotate left" and "rotate right" – M.M Sep 26 '16 at 22:08

1 Answers1

0

Thanks for the links. It looks like I am doing it quite well anyway. Here is my javascript function:

// Returns the new number
// This assumes the lowest bit of the number is on the right
// So going left puts the high number bits at the bottom on the right
// So going right puts the lowest bits to the left high number bits
// 'value' is the number you are doing it to
// 'shift' is how many bits you are shifting Minus is left, Plus is right
// 'maxbits' is the max bits in the number
function RotateLeftRight (value, shift, maxbits) {
    var doLeft;
    var ret, rightShift, leftShift, mask;

    if (maxbits <= 0) return 0; // Nothing to do
    ret = value & (Math.pow(2, maxbits) - 1); // Mask out the value so it has the correct bits to start with
    doLeft = shift < 0 ? true : false;
    if(doLeft) shift = -shift;
    shift %= maxbits;
    if(shift === 0) return ret;
    if (doLeft) {
        rightShift = maxbits - shift;
        leftShift = shift;
        mask = Math.pow(2, maxbits - shift) - 1;
    } else {
        rightShift = shift;
        leftShift = maxbits - shift;
        mask = Math.pow(2, shift) - 1;
    }
    return ((ret >> rightShift) | ((ret & mask) << leftShift));
};

I will mark this as answer, unless anyone would like to input any more.

Rewind
  • 2,554
  • 3
  • 30
  • 56