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

1 Answer

0 votes
fun printBits(value: Long, width: Int) {
    for (i in width - 1 downTo 0) {
        val mask = 1L shl i
        print(if ((value and mask) != 0L) "1" else "0")
    }
}

fun exactBitSet(pos1: Int, pos2: Int, value: Long): Boolean {
    if (pos1 < 0 || pos2 < 0 || pos1 >= 64 || pos2 >= 64) return false
    if (pos1 == pos2) return false

    val mask = (1L shl pos1) or (1L shl pos2)

    return value == mask
}

fun main() {
    val tests = listOf(
        Triple(0b1000010000L, Pair(4, 9), 10),
        Triple(0b0010000010L, Pair(1, 7), 10),
        Triple(0b0000100100L, Pair(2, 5), 10),
        Triple(0b1000010000L, Pair(3, 9), 10),
        Triple(0b1001010000L, Pair(4, 9), 10),
        Triple(0b1111111111L, Pair(4, 9), 10),
        Triple(0b0000000000L, Pair(4, 9), 10),
        Triple(0b1000010000L, Pair(4, 8), 10),
        Triple(1L, Pair(0, 0), 1),
        Triple(1L, Pair(0, 1), 1),
        Triple(0L, Pair(1, 1), 1)
    )

    for ((value, pair, width) in tests) {
        val (x, y) = pair
        printBits(value, width)
        print("  bits($x, $y)  ->  ")
        println(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

...