Bitwise Operators

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Bitwise Operators

or, What the 0xff is he talking about?

Math is Hard
especially when you only have two values

Why use bitwise operators?

Some iOS methods call for them

Handy way to create non-exclusive flags

Can streamline code

Lots of fun

What is a bitwise operation?

Works on a single bit, or set of bits

Direct bit-twiddling

WHAT??

Consider a number: 1

Its binary reprsentation is 00000001 (in a single


byte view)

Consider another number: 2

Its binary representation is 00000010

What are the operators?

& (bitwise and)

| (bitwise or)

~ (bitwise not)

^ (bitwise nor)

>> (shift right)

<< (shift left)

Bitwise AND

00000001 & 00001000 == 00000000

01010101 & 00010001 == 00010001

11111111 & 00000001 == 00000001

11110000 & 00001111 == 00000000

Bitwise OR

00010001 | 00000001 == 00010001

00010000 | 11111111 == 11111111

10101010 | 01010101 == 11111111

10011001 | 00000010 == 10011011

Bitwise NOT

~10101010 == 01010101

~11111111 == 00000000

~00000000 == 11111111

~00010010 == 11101101

Bitwise XOR

00010001 ^ 00000001 == 00010000

11110000 ^ 00001111 == 11111111

10101010 ^ 00100010 == 10001000

00100101 ^ 11001100 == 11101001

Bitwise shift

00000001 << 3 == 00001000

00000010 << 1 == 00000100

00001000 >> 1 == 00000100

00111000 >> 3 == 00000111

Actual use

Create a flag

NSInteger kSpecialFlag = (1<<0);

NSInteger kSpecialFlag2 = (1<<1);

if (value & kSpecialFlag) {[self doSomething];}

Creating multiple flags


typedef enum eFlagValues
{
flag_one = (1<<0),
flag_two = (1<<1),
flag_three = (1<<2)
}flagValues;

using NS_ENUM
NS_ENUM(NSInteger, myEnum)
{
opt_one = (1<<0),
opt_two = (1<<1),
opt_three = (1<<2)
};

NS_OPTIONS
NS_OPTIONS(NSInteger, myOptions)
{
option_one,
option_two
};

What not to do

Refactor your already-working code

Be clever

Spend multiple days debugging what could


otherwise be simple code

What to do

Look for non-exclusive option passing


opportunities

Understand how passing flags works in practice

Practice counting in binary

You might also like