简体   繁体   English

这两个代码片段之间有区别吗?如果有,那是什么?

[英]is there a difference between these two snippets of code and if yes what is it?

 function addBinary(a,b) { let sum= a+b if (sum<0){ sum=0xffffffff+sum+1 } return parseInt(sum).toString(2) }

and especially the logic of how 0xffffffff has been used to achieve same result尤其是如何使用 0xffffffff 来实现相同结果的逻辑

 function decimalToBinary(decimal){ return (decimal >>> 0).toString(2); } function addBinary(a,b) { return decimalToBinary(a+b); }

The >>> operator always interprets the given number as an unsigned 32 bit number. >>>运算符始终将给定数字解释为无符号32 位数字。 When the second operand is 0, nothing changes to that and the result is unsigned.当第二个操作数为 0 时,没有任何变化,结果是无符号的。

So for instance, -1 in binary is 0xffffffff in signed 32-bit, where the most significant bit (at the left) is the sign bit.例如,二进制中的 -1 是有符号 32 位中的 0xffffffff,其中最高有效位(左侧)是符号位。 But because exceptionally the >>> does not interpret that as a sign bit, it actually is seen as a positive number, ie 0xffffffff.但是因为异常>>>将其解释为符号位,它实际上被视为一个正数,即 0xffffffff。 Compared to the original -1 that is 0x100000000 more!比原来的-1多了0x100000000! This is always the difference for negative inputs.这始终是负输入的差异。 For -2 you'll get 0xfffffffe, for -3 you'll get 0xfffffffd, ...etc.对于-2,您将获得0xffffffffe,对于-3,您将获得0xfffffffd,...等等。

The first function emulates this.第一个函数模拟了这一点。 If sum is negative, we must do something, as the other function (using >>> ) will never return a negative number.如果sum是负数,我们必须做点什么,因为另一个函数(使用>>> )永远不会返回负数。

The idea is to add that 0x100000000 difference.这个想法是添加 0x100000000 差异。 In fact, the author of this function was prudent, and evidently didn't want to work with numbers that exceed the 32 bit range, so 0x100000000 was off the board (it uses 33 bits).事实上,这个函数的作者是谨慎的,显然不想使用超过 32 位范围的数字,所以 0x100000000 被排除在外(它使用 33 位)。 But one can split the job into parts.但是可以将工作分成几部分。 We can add one less (0xffffffff) to the sum, and then add the remaining 1. This is just a theoretical game though.我们可以在总和中减去一个(0xffffffff),然后再加上剩下的 1。不过这只是一个理论游戏。 In JavaScript there is no problem in adding 0x100000000, so they could just as well have done that.在 JavaScript 中添加 0x100000000 没有问题,所以他们也可以这样做。 In other languages however, those that use 32 bit numbers, it would be necessary to first add 0xffffffff and only then 1.然而,在其他语言中,使用 32 位数字的语言,必须先添加 0xffffffff,然后才添加 1。

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

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