How to clear bits in the given range in Swift

1 Answer

0 votes
import Foundation

// Print bits of a 32-bit integer
func printBits(_ x: UInt32, _ label: String) {
    // Convert to binary and pad to 32 bits
    let bits = String(x, radix: 2).padLeft(to: 32, with: "0")
    print("\(label): \(bits)")
}

// Clear bits in range [l, r] inclusive (0 = least significant bit)
func clearBits(_ x: UInt32, _ l: Int, _ r: Int) -> UInt32 {
    if l < 0 || r > 31 || l > r {
        fatalError("Invalid bit range")
    }

    // maskLeft:
    // Create a mask with 1s above bit r and 0s from bit r down to 0.
    // Example: r = 5 → maskLeft = 11111111 11111111 11111111 11000000
    let maskLeft: UInt32 = ~UInt32(0) << UInt32(r + 1)
    printBits(maskLeft, "maskLeft ")

    // maskRight:
    // Create a mask with 1s below bit l and 0s from bit l upward.
    // Example: l = 3 → maskRight = 00000000 00000000 00000000 00000111
    let maskRight: UInt32 = (1 << UInt32(l)) - 1
    printBits(maskRight, "maskRight")

    // Combine both masks:
    // maskLeft keeps bits above r.
    // maskRight keeps bits below l.
    // The range [l, r] becomes 0s.
    let mask: UInt32 = maskLeft | maskRight
    printBits(mask, "mask     ")

    return x & mask
}

// Main program
let value: UInt32 = 0b11111100111111001111110011111100

let l = 3   // start bit
let r = 10  // end bit

let result = clearBits(value, l, r)

printBits(value,  "Before   ")
printBits(result, "After    ")


// --- Utility extension for padding strings ---
extension String {
    func padLeft(to length: Int, with char: Character) -> String {
        if self.count >= length { return self }
        return String(repeating: char, count: length - self.count) + self
    }
}




/*
run:

maskLeft : 11111111111111111111100000000000
maskRight: 00000000000000000000000000000111
mask     : 11111111111111111111100000000111
Before   : 11111100111111001111110011111100
After    : 11111100111111001111100000000100

*/

 



answered Dec 30, 2025 by avibootz
...