While perusing Apple’s Swift language guide, I came across an interesting section regarding bit manipulation. Unbeknownst to me, Swift sports the same bitwise and bit shifting operators used by both C and Objective-C. Here’s a recap:
The Bitwise AND
& operator combines the bits of two numbers, maintaining the value of 1 for each bit ONLY if they are both 1.
The Bitwise OR
| operator combines the bits of two numbers, maintaining a value of 1 for each bit that is 1 in EITHER of the pertaining numbers.
The Bitwise XOR
^ operator (exclusive or) combines the bits of two numbers, maintaining a value of 1 for each bit ONLY if the value is different between each number.
The Bitwise NOT
~ operator ‘flips’ each bit of the input number.
The Bitwise Left Shift
<< operator does exactly what the name infers - shifts all bits to the left. Using the operator requires specification to how many spaces the numbers bits should be shifted. A left shift essentially doubles the current integer amount. An important tidbit (bit humor?) is that Swift does not allow an operator to overflow by default, meaning if bits are shifted beyond integer bounds a crash will occur.
The Bitwise Right Shift
>> operator is just like its left counterpart, except that the input bits are shifted to the right. An important difference is that a right shifted number will be capped at zero (i.e. if shifted beyond its bounds, the result will default to 0).
While working with a designer it is not uncommon to receive a color value represented in hexadecimal rather than RGB decimal format. Rather than converting these values using one of the numerous conversion tools available, lets instead utilize what we’ve learned about bit manipulation to create our own handy UIColor extension which converts these values for us.
Here’s a quick rundown of how it works. The hexadecimal number system uses 16 distinct symbols to represent the values 0 - 15 (0-9 and A-F respectively). Each hexadecimal digit consists of 8 bits (a byte), which allows the representation of any number from 0 - 255. Using this information, we can extract each red, green and blue value by isolating its corresponding bits.
Starting with red, we isolate the component by ANDing our hex number with the maximum possible number of bits (FF). Next we shift our value for red to the right 16 bits to make sure it resides in the 0-255 bounds. The same process is used for both green and blue, with the exception of the number of bits required in the right shift step (8 and 0 respectively). Each component is casted to a CGFloat to ensure the proper type, then used to initialize a UIColor using each respective RGB value. We can then create UIColor’s like this:
Another worthy addition to the toolbox!
Subscribe via RSS