1

I was looking into how one uses the UISwipeGestureRecognizer class in Objective-C and happened to run across an enum named UISwipeGestureRecognizerDirection.

Apple defines this as:

typedef enum {
   UISwipeGestureRecognizerDirectionRight = 1 << 0,
   UISwipeGestureRecognizerDirectionLeft  = 1 << 1,
   UISwipeGestureRecognizerDirectionUp    = 1 << 2,
   UISwipeGestureRecognizerDirectionDown  = 1 << 3
} 

I wasn't sure how the compiler interpreted the above, specifically the << operator. From looking it up, it appears to be the bitwise shift left - But I am afraid I dont understand how the operator works above.

Any direction is greatly appreciated. Thanks in advance!

noobzilla
  • 1,095
  • 2
  • 11
  • 17

2 Answers2

3

In a computer, integer numbers are represented as 1's and 0's.

So for a 1 bit computer, we can only use 1 or 0:

0 or 1 - 1 is the maximum number.

0 = 0
1 = 1

2-bit computer: - 3 is the maximum number. Remember you aren't counting from 0 to 9. You can only count to 1 then you have to increase the next column to the left.

00 = 0 + 0 = 0
01 = 0 + 1 = 1
10 = 2 + 0 = 2
11 = 2 + 1 = 3

3-bit computer: - 7 is the maximum number

000 = 0 + 0 + 0 = 0
001 = 0 + 0 + 1 = 1
010 = 0 + 2 + 0 = 2
011 = 0 + 2 + 1 = 3
100 = 4 + 0 + 0 = 4 
101 = 4 + 0 + 1 = 5
110 = 4 + 2 + 0 = 6
111 = 4 + 2 + 1 = 7 

All left bit-shifting (1<<3) means is place a 1 at the right most column (the zero position) and move the specified number of places to the left.

001 - 1<<0 -- Move it 0 times - Value is 1
010 - 1<<0 -- Move it 1 times - Value is 2
100 - 1<<0 -- Move it 2 times - Value is 4

Here's a table to help you think about an 8-bit computer:

|    7   |    6   |     5   |    4    |   3   |    2   |    1    |   0  |

|     128|      64|       32|       16|       8|      4|        2|     1|

|     2^7|    2^6 |      2^5|      2^4|     2^3|    2^2|      2^1|   2^0|

|1 << 7  |  1 << 6 | 1 << 5 | 1 << 4  | 1 << 3 | 1 << 2 | 1 << 1 | 1 << 0 |
h4labs
  • 765
  • 1
  • 10
  • 21
  • Thanks for taking the time to put down such a great detailed answer. I am familiar with the binary to integer conversion. Had never run into the bitwise operator before, and didnt put two and two together on how it worked. Thanks again! – noobzilla Jul 12 '13 at 09:55
1

It is a bitwise shift left. This is the equivalent of

typedef enum {
   UISwipeGestureRecognizerDirectionRight = 1,
   UISwipeGestureRecognizerDirectionLeft  = 2,
   UISwipeGestureRecognizerDirectionUp    = 4,
   UISwipeGestureRecognizerDirectionDown  = 8
} 

It's a convenience to allow bitwise testing. The actual value means nothing much except that they all can be packed into one variable - enum values can be anything at all as long as they are unique.

Adam Eberbach
  • 12,309
  • 6
  • 62
  • 114