How to convert int to binary with leading zeros in Scala

1 Answer

0 votes
object BinaryConverter {

  /** Converts an integer to a binary string with leading zeros
    * - num: The integer value to convert
    * - bits: The target bit width determining the leading zeros
    */
  def intToBinary(num: Int, bits: Int): String = {
    // 1. Convert the integer to its raw binary string representation
    val binaryStr = Integer.toBinaryString(num)
    
    // 2. Pad with leading zeros using functional collection methods:
    //    - reverse the string so padding applies to the front (which becomes the end temporarily)
    //    - padTo pads the collection with '0' until it reaches the specified 'bits' length
    //    - reverse it back to normal orientation
    binaryStr.reverse.padTo(bits, '0').reverse
  }

  def main(args: Array[String]): Unit = {
    // Define the data provided
    val num: Int = 153

    // 1. Convert to an 8-bit binary representation (153 fits within 8 bits: 0 to 255)
    val binStr8 = intToBinary(num, 8)

    // 2. Convert to a 16-bit binary representation to demonstrate wider padding
    val binStr16 = intToBinary(num, 16)

    // Display the results
    println(s"Original Integer: $num")
    println(s"Binary (8-bit)  : $binStr8")
    println(s"Binary (16-bit) : $binStr16")
  }
}



/*
run:

Original Integer: 153
Binary (8-bit)  : 10011001
Binary (16-bit) : 0000000010011001

*/

 



answered 1 day ago by avibootz
...