Swift算子解释

时间:2016-04-22 19:47:03

标签: swift operators bitwise-operators

我试图将一些Swift代码转换为Javascript,但是因为我不知道Swift中的某些运算符是做什么的,所以我无法将其转换为J& #39;类似的Javascript表单。这是代码:

private var portMasks = [UInt8](count: 3, repeatedValue: 0)

var newMask = UInt8(newState.rawValue * Int(powf(2, Float(pinIndex))))
portMasks[Int(port)] &= ~(1 << pinIndex) //prep the saved mask by zeroing this pin's corresponding bit
newMask |= portMasks[Int(port)] //merge with saved port state
portMasks[Int(port)] = newMask
data1 = newMask<<1; data1 >>= 1  //remove MSB
data2 = newMask >> 7 //use data1's MSB as data2's LSB 

已经定义pinIndexport的位置UInt8

我没有寻找实际的转换 - 我可以自己做。只是从数学/程序化角度寻找对这些线路的影响的解释。

1 个答案:

答案 0 :(得分:0)

开始一个新的游乐场并将其复制到内部:

var port: UInt8 = 1
var pinIndex: UInt8 = 2
var newState: Int = 23

var portMasks = [UInt8](count: 3, repeatedValue: 0)

var newMask = UInt8(newState * Int(powf(2, Float(pinIndex))))
portMasks[Int(port)] &= ~(1 << pinIndex) //prep the saved mask by zeroing this pin's corresponding bit
newMask |= portMasks[Int(port)] //merge with saved port state
portMasks[Int(port)] = newMask
var data1 = newMask<<1; data1 >>= 1  //remove MSB
var data2 = newMask >> 7 //use data1's MSB as data2's LSB

你会在右侧看到效果。

<< >> move bits by that amount
| logical or
& logical and
~ logical negation

认为这就是这里使用的所有东西。基本上你的代码正在操作单个位(由1&lt;&lt;&lt; bitPosition引用)并打开或关闭它们。

这两行意思相同:

variable OPERATOR= something
variable = variable OPERATOR something

建议玩一下,然后回答具体问题。