19

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

vrwim
  • 13,020
  • 13
  • 63
  • 118
Graham
  • 217
  • 1
  • 2
  • 5
  • 1
    `<<` is quite well described (with illustrations) in [Advanced Operators](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html) in the official Swift documentation . – Martin R May 19 '15 at 18:05
  • Shifting bits is not a Swift feature, it's simply as it's called, shifting bits left or right, all languages implement that, there's different types of shifting, some will rotate, some won't, some will rotate with carry, etc.. I would recommend looking into bitwise operations and the binary numbering system – Mostafa Berg Jul 14 '16 at 14:41

2 Answers2

53

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
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • Sorry to resurrect an old answer, but wondering what the logical reason for doing it this way as opposed to 0, 1, 2, 3? – user1898712 Dec 14 '22 at 17:11
4

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.

Christian Schnorr
  • 10,768
  • 8
  • 48
  • 83