Other ways of performing modulo operation

家住魔仙堡 提交于 2019-11-28 01:34:41

问题


Some time ago I've seen somewhere a trick to perform modulo operation using bit operators. But now I cannot in any way perform proper operation. Anyone knows how to do it ? From what I remember it was faster than using %.


回答1:


The "trick" is to binary AND a value with 1. Any odd number must have the first bit set to 1.

So

var foo = 7;

if( foo & 1 ) { // true
}

Using a bitwise AND has a better performance in almost all platforms / browsers.

for(var loop = 0; loop < 10; loop++) {
    if( loop & 1 ) {
        console.log('I am ', loop, ' and I am odd!');
    }
}



回答2:


You can do the modulo of 2^k (a power of 2) by ANDing your value with (2^k)-1.



来源:https://stackoverflow.com/questions/6572670/other-ways-of-performing-modulo-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!