How to check whether only 2 bits in a number at a specific position are on (edge‑case‑safe) with Swift

1 Answer

0 votes
import Foundation

func printBits(_ value: UInt64, width: Int) {
    for i in stride(from: width - 1, through: 0, by: -1) {
        let mask = UInt64(1) << UInt64(i)
        print((value & mask) != 0 ? "1" : "0", terminator: "")
    }
}

func exactBitSet(_ pos1: Int, _ pos2: Int, _ value: UInt64) -> Bool {
    if pos1 < 0 || pos2 < 0 || pos1 >= 64 || pos2 >= 64 { return false }
    if pos1 == pos2 { return false }

    let mask = (UInt64(1) << UInt64(pos1)) | (UInt64(1) << UInt64(pos2))
    return value == mask
}

let tests: [(UInt64, Int, Int, Int)] = [
    (0b1000010000, 4, 9, 10),
    (0b0010000010, 1, 7, 10),
    (0b0000100100, 2, 5, 10),
    (0b1000010000, 3, 9, 10),
    (0b1001010000, 4, 9, 10),
    (0b1111111111, 4, 9, 10),
    (0b0000000000, 4, 9, 10),
    (0b1000010000, 4, 8, 10),
    (1, 0, 0, 1),
    (1, 0, 1, 1),
    (0, 1, 1, 1)
]

for (value, x, y, width) in tests {
    printBits(value, width: width)
    print("  bits(\(x), \(y))  ->  \(exactBitSet(x, y, value))")
}


/*
OUTPUT:

1000010000  bits(4, 9)  ->  true
0010000010  bits(1, 7)  ->  true
0000100100  bits(2, 5)  ->  true
1000010000  bits(3, 9)  ->  false
1001010000  bits(4, 9)  ->  false
1111111111  bits(4, 9)  ->  false
0000000000  bits(4, 9)  ->  false
1000010000  bits(4, 8)  ->  false
1  bits(0, 0)  ->  false
1  bits(0, 1)  ->  false
0  bits(1, 1)  ->  false
   
*/

 



answered Apr 4 by avibootz

Related questions

...