gpt4 book ai didi

swift - Swift 中的 &<< 和 << 运算符有什么区别?

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:28 24 4
gpt4 key购买 nike

Swift 中的 &<< 和 << 运算符有什么区别?看起来他们返回相同的结果:

print(2 << 3) // 16
print(2 &<< 3) // 16

最佳答案

FixedWithInteger 协议(protocol)定义了“屏蔽左移运算符” &<< 作为

Returns the result of shifting a value’s binary representation the specified number of digits to the left, masking the shift amount to the type’s bit width.

Use the masking left shift operator (&<<) when you need to perform a shift and are sure that the shift amount is in the range 0..<lhs.bitWidth. Before shifting, the masking left shift operator masks the shift to this range. The shift is performed using this masked value.

因此,如果移位量大于或等于左操作数的位宽,结果可能会有所不同:示例:

print(2 << 70) // 0
print(2 &<< 70) // 128

这里的移位量(70)大于Int的bitwith (64),所以2 << 70评估为零。在第二行中,数字向左移动了 70 % 64 = 6 位。

还有一个类似的“掩码右移运算符”&>> .示例:

let x = Int8.min        // -128 = 0b10000000
print(Int8.min >> 8) // -1 = 0b11111111
print(Int8.min &>> 8) // -128 = 0b10000000

这里第一个结果是-1因为向右移动一个有符号整数会用符号位填充左边的空位。第二个结果是-128。因为偏移量为零:8 % 8 = 0 .

命名和预期用途也在 SR-6749 中描述。 :

The goal of the operator, however, is never to have this wrapping behavior happen — it's what you use when you have static knowledge that your shift amount is <= the bitWidth. By masking, you and the compiler can agree that there's no branch needed, so you get slightly faster code without zero branching and zero risk of undefined behavior (which a negative or too large shift would be).

The docs are confusing because they give an example I don't think anyone would ever intentionally write—relying on the wrapping behavior to use some out of bounds value for the shift amount.

因此使用掩码移位运算符可以提高性能。许多示例可以在 Swift 标准库的源代码中找到,例如 UTF8.swift .

关于swift - Swift 中的 &<< 和 << 运算符有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com