How do you find the position of the most significant bit (MSB) of an unsigned integer in Scala

2 Answers

0 votes
object MostSignificantBitProgram {

  /**
   * Returns the zero-based position of the most significant set bit (MSB)
   * in an unsigned 32-bit integer.
   *
   * Examples:
   *   1  -> 0
   *   2  -> 1
   *   8  -> 3
   *   15 -> 3
   *
   * @param value
   *   Unsigned 32-bit integer represented as an Int.
   * @return
   *   Some(position) if at least one bit is set;
   *   None if value is 0.
   */
  def msbPosition(value: Int): Option[Int] = {
    if (value == 0) {
      None
    } else {
      Some(31 - Integer.numberOfLeadingZeros(value))
    }
  }

  def main(args: Array[String]): Unit = {
    val testValues: Seq[Int] = Seq(
      0,
      1,
      2,
      8,
      15,
      0x1234,
      0x80000000
    )

    testValues.foreach { value =>
      msbPosition(value) match {
        case Some(position) =>
          println(
            s"Value: ${Integer.toUnsignedString(value)}, " +
            s"MSB position: $position"
          )

        case None =>
          println(
            s"Value: ${Integer.toUnsignedString(value)}, no bits are set"
          )
      }
    }
  }
}


/*
run:

Value: 0, no bits are set
Value: 1, MSB position: 0
Value: 2, MSB position: 1
Value: 8, MSB position: 3
Value: 15, MSB position: 3
Value: 4660, MSB position: 12
Value: 2147483648, MSB position: 31

*/

 



answered Oct 1 by avibootz
0 votes
object MostSignificantBitProgram {

  /**
   * Returns the zero-based position of the most significant set bit (MSB)
   * in an unsigned 32-bit integer.
   *
   * Examples:
   *   1  -> 0
   *   2  -> 1
   *   8  -> 3
   *   15 -> 3
   *
   * @param value
   *   Unsigned 32-bit integer represented as an Int.
   * @return
   *   Some(position) if at least one bit is set;
   *   None if value is 0.
   */
  def msbPosition(value: Int): Option[Int] = {
      if (value == 0) {
        None
      } else {
        var currentValue: Int = value
        var position: Int = 0
    
        while ((currentValue >>> 1) != 0) {
          currentValue >>>= 1
          position += 1
        }
    
        Some(position)
      }
  }

  def main(args: Array[String]): Unit = {
    val testValues: Seq[Int] = Seq(
      0,
      1,
      2,
      8,
      15,
      0x1234,
      0x80000000
    )

    testValues.foreach { value =>
      msbPosition(value) match {
        case Some(position) =>
          println(
            s"Value: ${Integer.toUnsignedString(value)}, " +
            s"MSB position: $position"
          )

        case None =>
          println(
            s"Value: ${Integer.toUnsignedString(value)}, no bits are set"
          )
      }
    }
  }
}


/*
run:

Value: 0, no bits are set
Value: 1, MSB position: 0
Value: 2, MSB position: 1
Value: 8, MSB position: 3
Value: 15, MSB position: 3
Value: 4660, MSB position: 12
Value: 2147483648, MSB position: 31

*/

 



answered Oct 1 by avibootz
...