Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shift bits using Swift?

Tags:

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?

like image 327
user3762440 Avatar asked Jun 21 '14 08:06

user3762440


1 Answers

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
like image 51
zoma Avatar answered Nov 15 '22 09:11

zoma