Swift Bitwise Operators (with a couple of practical examples)
5 (3)

Click to rate this post!
[Total: 3 Average: 5]

Bitwise operators are rarely used in everyday swift programming
⚠️ : not to be confused by Logical Operators like “&&” and “||”

It’s mainly used to perform operations on individual bits,  they are extremely useful and used in FlagsGraphicsNetworkingEncryption

OperatorDescription
Binary AND
|    Binary OR
^   Binary XOR
~    Binary One’s Complement
<<   Binary Shift Left
>>    Binary Shift Right
Swift Bitwise Operators



First, a refresher on the truth table of XOR, it gives True if both A and B are Different

ABResult
TRUETRUEFALSE
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE
XOR Truth Table


The basic code to represent integers as bits, and each operator and it’s result … 🧐

extension Int {
    
    var binaryDescription: String {
        var binaryString = ""
        var internalNumber = self
        for _ in (1...self.bitWidth) {
            binaryString.insert(contentsOf: "\(internalNumber & 1)", at: binaryString.startIndex)
            internalNumber >>= 1
        }
        return "0b " + binaryString
    }
    
}

func bitwise_example() {
    
    let x1 = 0x1
    let x2 = 0x2

    print("x1\t", x1.binaryDescription )
    print("x2\t", x2.binaryDescription )
    
    let binary_and = (x1 & x2)
    let binary_or = (x1 | x2)
    let binary_xor = (x1 ^ x2)
    let binary_complement = (~x1)
    let binary_shiftL = (x1 << 1)
    let binary_shiftR = (x1 >> 1)

    print("&\t",  binary_and.binaryDescription )
    print("|\t", binary_or.binaryDescription )
    
    print("^\t", binary_xor.binaryDescription )
    print("~\t", binary_complement.binaryDescription )
    print("<<\t", binary_shiftL.binaryDescription )
    print(">>\t", binary_shiftR.binaryDescription )
    
}

Output

x1	 0b 0000000000000000000000000000000000000000000000000000000000000001
x2	 0b 0000000000000000000000000000000000000000000000000000000000000010
&	 0b 0000000000000000000000000000000000000000000000000000000000000000
|	 0b 0000000000000000000000000000000000000000000000000000000000000011
^	 0b 0000000000000000000000000000000000000000000000000000000000000011
~	 0b 1111111111111111111111111111111111111111111111111111111111111110
<<	 0b 0000000000000000000000000000000000000000000000000000000000000010
>>	 0b 0000000000000000000000000000000000000000000000000000000000000000

Real Life Usage for them:

1- Color Format Conversion
Most probably, you would have such an extension in your boilerplate iOS app, it converts HEX colors into UIColor.

extension UIColor {
   convenience init(red: Int, green: Int, blue: Int) {
       assert(red >= 0 && red <= 255, "Invalid red component")
       assert(green >= 0 && green <= 255, "Invalid green component")
       assert(blue >= 0 && blue <= 255, "Invalid blue component")

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
   }

   convenience init(rgb: Int) {
       self.init(
           red: (rgb >> 16) & 0xFF,
           green: (rgb >> 8) & 0xFF,
           blue: rgb & 0xFF
       )
   }
}

2- Quick & Dirty hashing

let a = 4012
let b = 8102
let c = 9101

func dirtyHash(a: Int, b: Int, c: Int) -> Int{
    return ( a ^ b ^ c ^ 9999)
}

3- Base64 Encoding

Base64 encoding converts a series of 8 bit bytes into 6 bit character lookup indexes. (SHIFT)ing, (AND)ing, (OR)ing, (NOT)ing are used for implementing the bit operations necessary for Base64 encode/decode.

4- Checking if a number is Odd/Even.

func isEven(number: Int) -> Bool{
    return ((number & 0x1) == 0)
}

func isOdd(number: Int) -> Bool{
    return ((number & 0x1) > 0)
}

5- Solving Problems efficiently and in a performant way.
Write a program to swap the value of two variable.

Using temporary variable

c =  a; a = b; b = c; 

Without using temporary variable

a = a+b; b = a-b; a = a-b; 

Using bitwise operator

a = a^b; b = a^b; a = a^b; 

6- Calculating valid network addresses for a subnet

7- Calculating Permission in Role-based access control systems, RBAC.

8- Calculating Inverse Square Root very fastly
http://h14s.p5r.org/2012/09/0x5f3759df.html

Also:

Some people use bitwise operators to handle multiple error code together, each bit can hold a separate value.

N-bitmap can be a really cool and compact data structure.

Easily Tiling Images in interface builder, without code !
5 (1)

Click to rate this post!
[Total: 1 Average: 5]
images, with and without tiling

Tiling images in interface builder directly without code is easy…

1- add an image into assets catalogue.
2- select the asset, go to “editor” menu, then choose “Show Slicing”.
3- the asset image will show up as darker, with a button labeled “Start Slicing”, and you will be able to select the slicing type.


4- select how you want the image tiled, in normal cases you will have the setup like this, zeroed Left, Right, Top and Bottom, and the Width & Height as the image dimensions.


5- for tilability, the image content mode should be fill, not fit.

Keep experimenting, and go wild with your Imagination, sample of playing with small tilable images I have..








Why my 0.3 MB image occupies around 10 MB on RAM?
5 (2)

Click to rate this post!
[Total: 2 Average: 5]

You are writing an application that has a long list of entries, with each entry containing an image, the total download size of all images is about 10 MB, but the images take around 200 ~ 300 MB on RAM, you wonder why 🧐?

RAM normally does not understand images that are compressed, they are stored as raw bitmaps, even if the image is compressed, it gets inflated into memory as a raw image.

Image Size on RAM = (pixels height × pixels width × color depth bytes)

The following image takes around 300 KB on disk and has an sRGB color profile, which is 24 bits (8 bits per channel).

Unsplash (CC0)

The size of the image on the RAM would be:

Image Size on RAM = (1665  ×  2081 × 3) bytes = 9.8MB

In Swift, Kingfisher comes with an option to downsize images according to the screen scale, so you can have images in a reasonable size even if they come largely from the server.

import UIKit
import Kingfisher

extension UIImageView {
    
    func setImageAsThumb(url:String) {
        let formattedURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        let scale = UIScreen.main.scale
        let resizingProcessor = ResizingImageProcessor(referenceSize: CGSize(width: 50.0 * scale, height: 50.0 * scale))
        self.kf.setImage(with: URL(string: formattedURL), placeholder: nil, options: [.processor(resizingProcessor)])
    }

}