按位与运算(&)和求余运算(%)的联系
更新于2018-12-24 15:31:34
性能对比
求余运算:a % b就相当与a - (a / b) * b 的运算
按位与运算:是CPU的一条指令
在什么特殊场景下,能用与运算&替代求余运算%来提高效率呢?
在对10进行求余运算的时候,我们发现,余数总是整数中的个位上的数字,而不用管其他位是什么;
在按位与运算中,我们经常需要使用位操作符&来取某些位上的值,例如使用0xff&0x17ae来获取低8位的值0xae,如果求余结果值的范围刚好跟是[0,求余的底数(a%b中的b)]集合(集合元素只有0与b)一样,那么低位就是求余的结果。
例子:23%16 == 7等价于0x17 & 0x0F == 0x07,因此,当需要对2的次幂进行求余时,可以是使用&运算符来代替,效率会提高很多。当x = 2 ^ n(n为自然数)时,a % x = a & (x - 1)。
<li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#csdnc-thumbsup"></use> </svg><span class="name">点赞</span> <span class="count"></span> </a></li> <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{"mod":"popu_824"}"><svg class="icon" aria-hidden="true"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-csdnc-Collection-G"></use> </svg><span class="name">收藏</span></a></li> <li class="tool-item tool-active is-share"><a href="javascript:;"><svg class="icon" aria-hidden="true"> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-csdnc-fenxiang"></use> </svg>分享</a></li> <!--打赏开始--> <!--打赏结束--> <li class="tool-item tool-more"> <a> <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg> </a> <ul class="more-box"> <li class="item"><a class="article-report">文章举报</a></li> </ul> </li> </ul> </div> </div> <div class="person-messagebox"> <div class="left-message"><a href="https://blog.csdn.net/jiangyupeng"> <img src="https://profile.csdnimg.cn/F/7/D/3_jiangyupeng" class="avatar_pic" username="jiangyupeng"> <img src="https://g.csdnimg.cn/static/user-reg-year/2x/12.png" class="user-years"> </a></div> <div class="middle-message"> <div class="title"><span class="tit"><a href="https://blog.csdn.net/jiangyupeng" data-report-click="{"mod":"popu_379"}" target="_blank">诗景莫</a></span> </div> <div class="text"><span>发布了26 篇原创文章</span> · <span>获赞 19</span> · <span>访问量 1万+</span></div> </div> <div class="right-message"> <a href="https://im.csdn.net/im/main.html?userName=jiangyupeng" target="_blank" class="btn btn-sm btn-red-hollow bt-button personal-letter">私信 </a> <a class="btn btn-sm bt-button personal-watch" data-report-click="{"mod":"popu_379"}">关注</a> </div> </div> </div> </article>