What does shift left (<<) actually do in Swift?

我的未来我决定 提交于 2019-12-01 01:11:59

问题


I'm messing around with a Flappy Bird clone, and i can't figure out what the meaning of the following code is

let birdCategory: UInt32 = 1 << 0
let worldCategory: UInt32 = 1 << 1
let pipeCategory: UInt32 = 1 << 2
let scoreCategory: UInt32 = 1 << 3

Sorry if this is obvious, i've tried looking for the answer but couldn't find it. Thanks


回答1:


That's the bitwise left shift operator

Basically it's doing this

// moves 0 bits to left for 00000001
let birdCategory: UInt32 = 1 << 0 

// moves 1 bits to left for 00000001 then you have 00000010 
let worldCategory: UInt32 = 1 << 1

// moves 2 bits to left for 00000001 then you have 00000100 
let pipeCategory: UInt32 = 1 << 2

// moves 3 bits to left for 00000001 then you have 00001000 
let scoreCategory: UInt32 = 1 << 3

You end up having

birdCategory = 1
worldCategory = 2
pipeCategory = 4
scoreCategory= 8



回答2:


First of all, you posted Swift code, not Objective-C.

But I would assume it's a byte shift just as in plain old C.

a << x is equivalent to a * 2^x. By shifting the bits one position to the left, you double your value. Doing so x times will yield 2^x times the value, unless it overflows, of course.

You can read about how numbers are represented in a computer here.



来源:https://stackoverflow.com/questions/30332724/what-does-shift-left-actually-do-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!