问题
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