How to remove multiple bits from a number and shift the remaining bits right to fill the gaps in Kotlin

1 Answer

0 votes
/*
    removeBitsAndShift(number, positions)
    -------------------------------------
    Removes multiple bit positions from a number and shifts the remaining bits
    right to fill the gaps.

    Important:
        Bits must be removed from highest → lowest position.
        Otherwise earlier removals shift the positions of later ones.
*/
fun removeBitsAndShift(number: Int, positions: List<Int>): Int {

    // Sort positions descending
    val sorted: List<Int> = positions.sortedDescending()

    var result: Int = number

    for (pos: Int in sorted) {
        val left: Int  = result shr (pos + 1)        // bits above removed bit
        val right: Int = result and ((1 shl pos) - 1) // bits below removed bit

        result = (left shl pos) or right             // merge
    }

    return result
}

/*
    printBinary(n)
    --------------
    Prints a 32-bit binary representation of an integer.
*/
fun printBinary(n: Int) {
    val binary: String = n.toString(2).padStart(32, '0')
    val grouped: String = binary.chunked(4).joinToString(" ")
    println(grouped)
}

fun main() {

    val number: Int = 1234                 // 0000 0000 0000 0000 0000 0100 1101 0010
    val positions: List<Int> = listOf(1, 3, 7) // remove bits 1, 3, 7 (0 = LSB)

    println("Original number in binary:")
    printBinary(number)

    val result: Int = removeBitsAndShift(number, positions)

    println("\nNumber after removing bits {1, 3, 7} and shifting remaining bits:")
    printBinary(result)

    println("\nResult as integer: $result")
}


/*
run:

Original number in binary:
0000 0000 0000 0000 0000 0100 1101 0010 

Number after removing bits {1, 3, 7} and shifting remaining bits:
0000 0000 0000 0000 0000 0000 1001 0100 

Result as integer: 148

*/

 



answered 1 day ago by avibootz

Related questions

...