Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,753 questions

55,518 answers

573 users

How to zero every n-bit from a number if that bit is 1 in Kotlin

1 Answer

0 votes
/*
    zeroBitsEveryStep(number, step)
    -------------------------------
    Zeros every `step`-th bit (0-based from LSB)
    but only if that bit is currently 1.

    Example:
        number = 536_870_911
        step = 3  → zero bits 0, 3, 6, 9, ...
*/
fun zeroBitsEveryStep(number: Int, step: Int): Int {
    var result = number

    var pos = 0
    while (pos < 32) {
        val mask = 1 shl pos

        // If the bit is 1, zero it
        if ((result and mask) != 0) {
            result = result and mask.inv()
        }

        pos += step
    }

    return result
}

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

fun main() {

    val number = 536_870_911   // 0001 1111 1111 1111 1111 1111 1111 1111
    val step   = 3             // zero bits 0, 3, 6, 9, ...

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

    val result = zeroBitsEveryStep(number, step)

    println("\nNumber after zeroing every $step bits (only if bit was 1):")
    printBinary(result)

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



/*
run:

Original number in binary:
0001 1111 1111 1111 1111 1111 1111 1111

Number after zeroing every 3 bits (only if bit was 1):
0001 0110 1101 1011 0110 1101 1011 0110

Result as integer: 383479222

*/

 



answered Jun 25 by avibootz
...