Grant Emerson

Into the Bitwise Spectrum

Into the Bitwise Spectrum — SwiftMoji Entry #23

Swift’s seamless combination of low-level power and high-level abstractions makes it a very flexible programming language. For low-level manipulation of raw data, Swift provides a complete set of bitwise operators. In the following example, we declare a HexadecimalColor that aliases the UInt32 type. The four bytes within a UInt32 can hold the 8-bit components for red, green, and blue. An orange color with value #FF872C can be declared as a hexadecimal literal in swift by removing the # and replacing it with a 0x prefix. We can then extract the RGB components from the color by using the bitwise AND (&) and right shift (>>) operators. The former sets all undesirable bits (those not set to one in the rhs) to 0. The latter then shifts those bits over by the number described on its rhs. This allows the color component to be converted to the appropriate decimal representation.

import Foundation

typealias HexadecimalColor = UInt32

let 🎨: HexadecimalColor = 0xFF872C // RGB(255, 135, 44)
let 🔴 = (🎨 & 0xFF0000) >> 16 // 255
let 💚 = (🎨 & 0x00FF00) >> 8 // 135
let 🔵 = 🎨 & 0x0000FF // 44
Tagged with: