How to convert int to binary with leading zeros in Kotlin

1 Answer

0 votes
// A function that 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
fun intToBinary(num: Int, bits: Int): String {
    // 1. num.toString(2) converts the integer to its raw binary string representation.
    // 2. .padStart(bits, '0') pads the left side of the string with '0' until 
    //    it reaches the specified bit length.
    return num.toString(2).padStart(bits, '0')
}

fun main() {
    // Define the data provided
    val num = 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("Original Integer: $num")
    println("Binary (8-bit)  : $binStr8")
    println("Binary (16-bit) : $binStr16")
}


/*
run:

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

*/

 



answered 1 day ago by avibootz
...