简体   繁体   English

当n为2^k时,如何证明m%n等价于m&(n-1)?

[英]How to prove m%n is equivalent to m&(n-1) when n is 2^k?

Notice that '%' is a remainder operator and '&' is a bitwise AND operator, and k is an integer bigger than 0.请注意,“%”是余数运算符,“&”是按位与运算符,k 是大于 0 的 integer。

Example:例子:

33%16=1 equivalent to 33&(16-1)=1

I found this equivalent in JDK1.8 ThreadLocalMap.我在 JDK1.8 ThreadLocalMap 中找到了这个等价物。 I know it is correct but don't how to prove it is correct.我知道这是正确的,但不知道如何证明它是正确的。 I would be appreciated if you could give some help.如果您能提供一些帮助,我将不胜感激。

m % n is the remainder of dividing m by n and is therefore a number between 0 and n-1, or between 0 and 2^k - 1. m % n是 m 除以 n 的余数,因此是介于 0 和 n-1 或 0 和 2^k - 1 之间的数字。

2^k in binary is one followed by k zeroes.二进制中的 2^k 是 1 后跟 k 个零。 2^k -1 is k contiguous ones. 2^k -1 是 k 个连续的。

m & n is m & (2^k - 1) is a number in which, in binary, the 1 bits must occur in the rightmost k bits. m & n是 m & (2^k - 1) 是一个数字,在二进制中,1 位必须出现在最右边的 k 位中。 It is therefore in the range 0 to 2^k - 1.因此它在 0 到 2^k - 1 的范围内。

QED. QED。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM