Bitwise shifting and operators in Swift
A bit is the smallest piece of information that can be 1 or 0 (on/off). Eight bits together are called a byte. A UInt8
in Swift is represented by 8 bits. The difference of this unsigned integer with the signed integer Int8
is that Int8
uses 1 bit to signify whether the integer is positive or negative. Having eight bits to represent a number means we can represent 2⁸ = 256 different numbers with UInt8
.
0 = 00000000 2 = 00000010 4 = 00000100 8 = 00001000
1 = 00000001 3 = 00000011 5 = 00000101 9 = 00001001
6 = 00000110 10 = 00001010
7 = 00000111 11 = 00001011
12 = 00001100
13 = 00001101
14 = 00001110
15 = 00001111
...
255 = 11111111
Bitwise shifting
This is easiest explained with an example: say we have the number 8 represented by 00001000
and we do a left shift <<
. This means that all bits will move one place to the left by removing the left bit and insert a new bit with the value 0
at the right. This will end up in number 16…