如何使用Swift移位?

时间:2014-06-21 08:35:36

标签: swift

在Objective-C中,代码是

uint16_t majorBytes;
[data getBytes:&majorBytes range:majorRange];
uint16_t majorBytesBig = (majorBytes >> 8) | (majorBytes << 8);

在Swift中

    var majorBytes: CConstPointer<UInt16> = nil

    data.getBytes(&majorBytes, range: majorRange)

aobut majorBytesBig怎么样?

1 个答案:

答案 0 :(得分:8)

Bit-Shifting-Syntax没有从ObjC变为Swift。只需查看Swift-Book中的Advanced Operators章节,就可以更深入地了解这里发生的事情。

// as binary: 0000 0001 1010 0101 (421)
let majorBytes: UInt16 = 421

// as binary: 1010 0101 0000 0000 (42240)
let majorBytesShiftedLeft: UInt16 = (majorBytes << 8)

// as binary: 0000 0000 0000 0001 (1)
let majorBytesShiftedRight: UInt16 = (majorBytes >> 8)

// as binary: 1010 0101 0000 0001 (42241)
let majorBytesBig = majorBytesShiftedRight | majorBytesShiftedLeft