我真的不明白为什么在下面的代码中,9、14、19、24的a * 51 & 52计算结果是false。我知道间隔是5,但为什么使用51和52,我应该使用什么数字,例如间隔6?
for( // loop :)
b=a=''; // b - result , a - numeric variable
a++<36; //
b+=a*51&52 // if "a" is not 9 or 14 or 19 or 24
? // return a random number or 4
(
a^15 // if "a" is not 15
? // genetate a random number from 0 to 15
8^Math.random()*
(a^20?16:4) // unless "a" is 20, in which case a random number from 8 to 11
:
4 // otherwise 4
).toString(16)
:
'-' // in other cases (if "a" is 9,14,19,24) insert "-"
);
return b2014年8月25日15:35更新:抱歉,可能我的问题有点不清楚。我想要一个逻辑或数学解释,为什么对于9、14、19、24,逐位比较只计算为false。我知道按位运算符是做什么的,以及它是如何工作的,但我真的不明白上面使用的模式的逻辑。这段代码实际上是为了生成随机的v4 UUID(参见https://gist.github.com/LeverOne/1308368)而摘录的,我将它命名为size optimised,而不是混淆代码。
发布于 2014-08-25 16:30:28
实际上,对于9、14、19、24,a*51&52的计算结果是0,即false (而不是true)。
如果您在编程模式下打开Windows计算器并键入9*51和52,您将自己看到它。
当然,这也有数学上的原因,你可以尝试调查更多…
发布于 2014-08-25 16:33:00
这很简单,就像这样:
51_10 is 110011_2
52_10 is 110100_2
9*52_10 = 459_10 is 111001011_2如果您使用a*51和52,并执行二进制和
00000110100 //52
00111001011 //459 = 51 * 9
01011001010 //714 = 51 * 14
01111001001 //969 = 51 * 19
10011001000 //1224 = 51 * 24你会得到
00000000000每次都是这样。0 =假。
Reference:wiki
https://stackoverflow.com/questions/25481755
复制相似问题