How to get the 4 least significant bits in a byte with Swift

1 Answer

0 votes
import Foundation

let value: UInt8 = 0b1101_0110        // 214
let lower4 = value & 0x0F             // 0b0110 = 6

print("value  (dec): \(value)")
print("lower4 (dec): \(lower4)")

// Generate basic binary strings
let vStr = String(value, radix: 2)
let lStr = String(lower4, radix: 2)

// Fix: Pad by repeating "0" at the beginning to reach the target length
let valueBin  = String(repeating: "0", count: max(0, 8 - vStr.count)) + vStr
let lower4Bin = String(repeating: "0", count: max(0, 4 - lStr.count)) + lStr

print("value  (bin):  \(valueBin)")  // Result: 11010110
print("lower4 (bin):  \(lower4Bin)") // Result: 0110



/*
run:

value  (dec): 214
lower4 (dec): 6
value  (bin):  11010110
lower4 (bin):  0110

*/

 



answered Dec 28, 2025 by avibootz
...