Saturday, December 9, 2023
HomeiOS DevelopmentSensible information to binary operations utilizing the UInt8 kind in Swift

Sensible information to binary operations utilizing the UInt8 kind in Swift

Representing numbers as integers

Now that we all know what sort of integers can be found in Swift, it is time to discuss a bit about what sort of numbers can we characterize utilizing these information sorts.


So there’s a minimal and most worth for every integer kind that we are able to retailer in a given variable. For instance, we won’t retailer the worth 69420 inside a UInt8 kind, as a result of there are merely not sufficient bits to characterize this big quantity. ?

Let’s study our 8 bit lengthy unsigned integer kind. 8 bit implies that we’ve got actually 8 locations to retailer boolean values (ones and zeros) utilizing the binary quantity illustration. 0101 0110 in binary is 86 utilizing the “common” decimal quantity format. This binary quantity is a base-2 numerical system (a positional notation) with a radix of two. The quantity 86 might be interpreted as:

  • 0*28+1*27+0*26+1*25+0*24 + 1*23+1*22+0*21+0*20
  • 0*128+1*64+0*32+1*16 + 0*8+1*4+1*2+0*1
  • 64+16+4+2
  • 86

We will convert forwards and backwards between decimal and binary numbers, it isn’t that tough in any respect, however let’s come again to this matter in a while. In Swift we are able to examine if a sort is a signed kind and we are able to additionally get the size of the integer kind via the bitWidth property.


Primarily based on this logic, now it is fairly simple that an 8 bit lengthy unsigned kind can solely retailer 255 as the utmost worth (1111 1111), since that is 128+64+32+16+8+4+2+1.

What about signed sorts? Properly, the trick is that 1 bit from the 8 is reserved for the optimistic / adverse image. Normally the primary bit represents the signal and the remaining 7 bits can retailer the precise numeric values. For instance the Int8 kind can retailer numbers from -128 til 127, for the reason that most optimistic worth is represented as 0111 1111, 64+32+16+8+4+2+1, the place the main zero signifies that we’re speaking a few optimistic quantity and the remaining 7 bits are all ones.

So how the hack can we characterize -128? Is not -127 (1111 1111) the minimal adverse worth? ?

Nope, that is not how adverse binary numbers work. With the intention to perceive adverse integer illustration utilizing binary numbers, first we’ve got to introduce a brand new time period known as two’s complement, which is a straightforward methodology of signed quantity illustration.

Fundamental signed quantity maths

It’s comparatively straightforward so as to add two binary numbers, you simply add the bits so as with a carry, similar to you’d do addition utilizing decimal numbers. Subtraction however is a bit tougher, however fortuitously it may be changed with an addition operation if we retailer adverse numbers in a particular approach and that is the place two’s complement is available in.

We could say that we might like so as to add two numbers:

  • 0010 1010 (+42)
  • 0100 0101 +(+69)
  • 0110 1111 =(+111)

Now let’s add a optimistic and a adverse quantity saved utilizing two’s complement, first we have to specific -6 utilizing a signed 8 bit binary quantity format:

  • 0000 0110 (+6)
  • 1111 1001 (one’s complement = inverted bits)
  • 1111 1010 (two’s complenet = add +1 (0000 0001) to 1’s complement)

Now we are able to merely carry out an addition operation on the optimistic and adverse numbers.

  • 0010 1010 (+42)
  • 1111 1010 +(-6)
  • (1) 0010 0100 =(+36)

So, you would possibly suppose, what is the take care of the additional 1 to start with of the 8 bit consequence? Properly, that is known as a carry bit, and in our case it will not have an effect on our remaining consequence, since we have carried out a subtraction as a substitute of an addition. As you may see the remaining 8 bit represents the optimistic quantity 36 and 42-6 is strictly 36, we are able to merely ignore the additional flag for now. ?

Binary operators in Swift

Sufficient from the speculation, let’s dive in with some actual world examples utilizing the UInt8 kind. To start with, we must always speak about bitwise operators in Swift. In my earlier article we have talked about Bool operators (AND, OR, NOT) and the Boolean algebra, now we are able to say that these features function utilizing a single bit. This time we’ll see how bitwise operators can carry out numerous transformations utilizing a number of bits. In our pattern circumstances it is all the time going to be 8 bit. ?

Bitwise NOT operator

This operator (~) inverts all bits in a quantity. We will use it to create one’s complement values.

let x: UInt8 = 0b00000110    
let res = ~x                 
print(String(res, radix: 2)) 

Properly, the issue is that we’ll preserve seeing decimal numbers on a regular basis when utilizing int sorts in Swift. We will print out the proper 1111 1001 consequence, utilizing a String worth with the bottom of two, however for some purpose the inverted quantity represents 249 in accordance with our debug console. ?

It’s because the which means of the UInt8 kind has no understanding in regards to the signal bit, and the eighth bit is all the time refers back to the 28 worth. Nonetheless, in some circumstances e.g. while you do low degree programming, akin to constructing a NES emulator written in Swift, that is the appropriate information kind to decide on.

The Knowledge kind from the Basis framework is taken into account to be a group of UInt8 numbers. Really you will discover numerous use-cases for the UInt8 kind in case you take a deeper take a look at the prevailing frameworks & libraries. Cryptography, information transfers, and so forth.

Anyway, you may make an extension to simply print out the binary illustration for any unsigned 8 bit quantity with main zeros if wanted. 0️⃣0️⃣0️⃣0️⃣ 0️⃣1️⃣1️⃣0️⃣

import Basis

fileprivate extension String {
    func leftPad(with character: Character, size: UInt) -> String {
        let maxLength = Int(size) - depend
        guard maxLength > 0 else {
            return self
        return String(repeating: String(character), depend: maxLength) + self

extension UInt8 {
    var bin: String {
        String(self, radix: 2).leftPad(with: "0", size: 8)

let x: UInt8 = 0b00000110   
print(String(x, radix: 2))  
let res = (~x) + 1          

We nonetheless have to supply our customized logic if we need to specific signed numbers utilizing UInt8, however that is solely going to occur after we all know extra in regards to the different bitwise operators.

Bitwise AND, OR, XOR operators

These operators works similar to you’d anticipate it from the reality tables. The AND operator returns a one if each the bits had been true, the OR operator returns a 1 if both of the bits had been true and the XOR operator solely returns a real worth if solely one of many bits had been true.

  • AND & – 1 if each bits had been 1
  • OR | – 1 if both of the bits had been 1
  • XOR ^ – 1 if solely one of many bits had been 1

Let me present you a fast instance for every operator in Swift.

let x: UInt8 = 42   
let y: UInt8 = 28   
print((x & y).bin)  
print((x | y).bin)  
print((x ^ y).bin)  

Mathematically talking, there may be not a lot purpose to carry out these operations, it will not offer you a sum of the numbers or different fundamental calculation outcomes, however they’ve a unique function.

You should use the bitwise AND operator to extract bits from a given quantity. For instance if you wish to retailer 8 (or much less) particular person true or false values utilizing a single UInt8 kind you need to use a bitmask to extract & set given elements of the quantity. ?

var statusFlags: UInt8 = 0b00000100

print(statusFlags & 0b00000100 == 4)   
print(statusFlags & 0b00010000 == 16)  
statusFlags = statusFlags & 0b11101111 | 16
statusFlags = statusFlags & 0b11111011 | 0
statusFlags = statusFlags & 0b11101111 | 0
statusFlags = statusFlags & 0b11101011 | 4

That is good, particularly in case you do not need to fiddle with 8 totally different Bool variables, however one there may be one factor that may be very inconvenient about this answer. We all the time have to make use of the appropriate energy of two, in fact we might use pow, however there’s a extra elegant answer for this challenge.

Bitwise left & proper shift operators

By utilizing a bitwise shift operation you may transfer a bit in a given quantity to left or proper. Left shift is basically a multiplication operation and proper shift is similar with a division by an element of two.

“Shifting an integer’s bits to the left by one place doubles its worth, whereas shifting it to the appropriate by one place halves its worth.” –

It is fairly easy, however let me present you a number of sensible examples so you will perceive it in a bit. ?

let meaningOfLife: UInt8 = 42

print(meaningOfLife << 1) 
print(meaningOfLife << 2) 
print(meaningOfLife << 3) 
print(meaningOfLife >> 1) 
print(meaningOfLife >> 2) 
print(meaningOfLife >> 3) 
print(meaningOfLife >> 4) 
print(meaningOfLife >> 5) 
print(meaningOfLife >> 6) 
print(meaningOfLife >> 7) 

As you may see we’ve got to watch out with left shift operations, for the reason that consequence can overflow the 8 bit vary. If this occurs, the additional bit will simply go away and the remaining bits are going for use as a remaining consequence. Proper shifting is all the time going to finish up as a zero worth. ⚠️

Now again to our standing flag instance, we are able to use bit shifts, to make it extra easy.

var statusFlags: UInt8 = 0b00000100

print(statusFlags & 1 << 2 == 1 << 2)

statusFlags = statusFlags & ~(1 << 2) | 0

statusFlags = statusFlags & ~(1 << 2) | 1 << 2

As you may see we have used numerous bitwise operations right here. For the primary examine we use left shift to create our masks, bitwise and to extract the worth utilizing the masks and at last left shift once more to match it with the underlying worth. Contained in the second set operation we use left shift to create a masks then we use the not operator to invert the bits, since we’ll set the worth utilizing a bitwise or perform. I suppose you may work out the final line based mostly on this information, but when not simply follow these operators, they’re very good to make use of as soon as you recognize all of the little the main points. ☺️

I believe I will lower it right here, and I will make simply one other put up about overflows, carry bits and numerous transformations, possibly we’ll contain hex numbers as properly, anyway do not need to promise something particular. Bitwise operations are usueful and enjoyable, simply follow & do not be afraid of a little bit of math. ?



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments