How to remove a bit from a number and shift all bits to the right to fill the gap in Kotlin

1 Answer

0 votes
/*
    Removes the bit at the given position and shifts all higher bits right.
*/
fun removeBitAndShift(number: Int, position: Int): Int {
    /*
        number = 22 (10110)
        position = 2 (0 = LSB)

        Bits: 1 0 1 1 0
                  ^ remove this bit

        left  = bits above removed bit
        right = bits below removed bit

        result = (left << position) | right
    */

    val left: Int = number shr (position + 1)          // bits above removed bit
    val right: Int = number and ((1 shl position) - 1) // bits below removed bit

    return (left shl position) or right                // merge shifted left + right
}

/*
    Prints a 32-bit binary representation of an integer.
*/
fun printBinary(value: Int) {
    /*
        Uses:
            value.toString(2) → binary string
            padStart(32, '0') → pad to 32 bits
            chunked(4) → group into 4-bit chunks
    */

    val binary: String = value.toString(2).padStart(32, '0')
    val grouped: String = binary.chunked(4).joinToString(" ")
    println(grouped)
}

fun main() {
    val number: Int = 22
    val position: Int = 2 // remove bit 2 (0 = LSB)

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

    val result: Int = removeBitAndShift(number, position)

    println()
    println("Number after removing bit $position and shifting remaining bits:")
    printBinary(result)

    println()
    println("Result as integer: $result")
}



/*
run:

Original number in binary:
0000 0000 0000 0000 0000 0000 0001 0110

Number after removing bit 2 and shifting remaining bits:
0000 0000 0000 0000 0000 0000 0000 1010

Result as integer: 10

*/

 



answered 1 day ago by avibootz

Related questions

...