user3762440
user3762440

Reputation: 51

How do I shift bits using Swift?

In Objective-C the code is

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

In Swift

    var majorBytes: CConstPointer<UInt16> = nil

    data.getBytes(&majorBytes, range: majorRange)

how aobut majorBytesBig?

Upvotes: 5

Views: 4562

Answers (1)

Dennis Zoma
Dennis Zoma

Reputation: 2641

The Bit-Shifting-Syntax has not changed from ObjC to Swift. Just check the chapter Advanced Operators in the Swift-Book to get a deeper understanding of what's going on here.

// 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

Upvotes: 8

Related Questions