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

1 Answer

0 votes
object BitCheck {

  def printBits(value: Long, width: Int): Unit = {
    for (i <- (0 until width).reverse) {
      val mask = 1L << i
      print(if ((value & mask) != 0) "1" else "0")
    }
  }

  def 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 << pos1) | (1L << pos2)
    value == mask
  }

  def main(args: Array[String]): Unit = {
    val tests = Seq(
      (0b1000010000L, 4, 9, 10),
      (0b0010000010L, 1, 7, 10),
      (0b0000100100L, 2, 5, 10),
      (0b1000010000L, 3, 9, 10),
      (0b1001010000L, 4, 9, 10),
      (0b1111111111L, 4, 9, 10),
      (0b0000000000L, 4, 9, 10),
      (0b1000010000L, 4, 8, 10),
      (1L, 0, 0, 1),
      (1L, 0, 1, 1),
      (0L, 1, 1, 1)
    )

    for ((value, x, y, width) <- tests) {
      printBits(value, width)
      print(s"  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 3 by avibootz

Related questions

...