2016-09-26 41 views
0

我有一個按位形式的數字(例如10101111000010 ...),30位數字。讓它成爲按位移 -

abcdefgh.....wxyz 

我想要一個漂亮的方式來遊移,所以它停留30位,但它被轉移3,但前三名然後在底部放。

defgh.....wxyzabc 

所以一切都向上移動3,但前三位數字放在右邊。

這怎麼可以做得整齊。

我也需要反向操作,所以如果我開始與

abcdefgh....wxyz 

它移到其他方式

xyzabcdefgh....w 

這是在30位地區全部完成。 30位數字區域之外的所有位都保留爲0.

這一切都必須單方面處理,因爲JavaScript只能可靠地識別高達52/53位的數字。

我有什麼,但迄今爲止它看起來呸:

var digits = 30; 
var shift = 3; 
var value = 167596277; 
var shiftedValue = (value >> shift) | (value & (Math.pow(2, shift)-1)) << (digits - shift); 
+0

你正試圖創建一個「桶/圓形移位器」取決於這可能是一個重複的語言* C++:* http://stackoverflow.com/questions/25799215/bitwise-rotation-circular-shift和另一個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

+0

這就是所謂的「左轉」和「右轉」 –

回答

0

感謝您的鏈接。無論如何,我看起來很好。這裏是我的javascript功能:

// 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)); 
}; 

我會將此標記爲答案,除非有人想再輸入。

+1

這段代碼似乎不必要的複雜 – harold

+0

請建議一個替代那完成所有上述。 – Rewind