``>> 是什么意思? 1` 是什么意思?

发布于 2024-12-04 22:47:56 字数 148 浏览 3 评论 0原文

我正在阅读 underscore.js 代码。我发现了这个:

var mid = (low + high) >> 1;

>> 是什么? 1 做什么?为什么它有用?

I'm reading through the underscore.js code. I found this:

var mid = (low + high) >> 1;

What does >> 1 do? Why is it useful?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

抱着落日 2024-12-11 22:47:56

它将左侧的位向右移动一位。它相当于除以 2。

在“旧时代”,这比简单的除法要快,尽管我怀疑它在下划线的情况下会产生很大的差异。

It shifts the bits in the left side to the right by one bit. It is equivalent to dividing by 2.

In 'Ye olden times' this was faster than simply dividing, though I doubt it would make a whole lot of difference in underscore's case.

成熟的代价 2024-12-11 22:47:56

>> 是符号传播右移运算符。它将(low + high)的位模式右移1位,并将最左边的位复制到左边的位置。它实际上与 Math.floor((low + high) / 2) 相同。

如果我没有指出使用 (low + high) >> 的一个微妙错误,那我就是失职了。 1 在二分搜索中计算数组的中点,这可能会导致溢出。 <代码>(低+高)>>> 1,其中 >>> 是零填充右移运算符,没有溢出错误。

>> is the sign propagating right shift operator. It shifts the bit pattern of (low + high) right by 1 place and the leftmost bit is copied to the left place. It's effectively same as Math.floor((low + high) / 2).

I would be remiss if I didn't point out a subtle bug with using (low + high) >> 1 to compute the mid point of an array in binary search which can cause overflow. (low + high) >>> 1 where >>> is zero filling right shift operator, is devoid of overflow bug.

傲性难收 2024-12-11 22:47:56

这是按位右移。对于整数来说,相当于除以二;对于 JavaScript 数字,它与 Math.floor((low + high) / 2) 大致相同,但完全避免了浮点。

That's a bitwise right shift. For integers, it is equivalent to dividing by two; for JavaScript numbers, it is roughly the same as Math.floor((low + high) / 2) but avoids the floating point altogether.

再见回来 2024-12-11 22:47:56

它可能是为了将值保持为整数。在某些情况下,此处除以 2 可能会将结果转换为浮点数,例如,如果 (low + high) 为奇数。

这两个操作并不完全等同:

> (5+2)/2
3.5
> (5+2)>>1
3

不过,对于这种特殊用途,有更好的用于查找两个数字的中点的习语。

It's probably there to keep the value an integer. Dividing by 2 here may convert the result to a floating point number in some cases, for example, if (low + high) is odd.

The two operations are not exactly equivalent:

> (5+2)/2
3.5
> (5+2)>>1
3

For this particular use, though, there are better idioms for finding the midpoint of two numbers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文