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,685 questions

55,437 answers

573 users

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

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

// Removes the bit at the given position and shifts all higher bits right.
func 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
    */

    left := number >> (position + 1)          // bits above removed bit
    right := number & ((1 << position) - 1)   // bits below removed bit

    return (left << position) | right         // merge shifted left + right
}

// Prints a 32-bit binary representation of an integer.
func printBinary(value int) {
    /*
        Uses:
            fmt.Sprintf("%b", value) → binary string
            pad to 32 bits using strings.Repeat
            group into 4-bit chunks for readability
    */

    binary := fmt.Sprintf("%b", value)
    if len(binary) < 32 {
        binary = strings.Repeat("0", 32-len(binary)) + binary
    }

    // Group into 4-bit chunks
    for i := 0; i < 32; i += 4 {
        fmt.Print(binary[i:i+4], " ")
    }
    fmt.Println()
}

func main() {
    number := 22
    position := 2 // remove bit 2 (0 = LSB)

    fmt.Println("Original number in binary:")
    printBinary(number)

    result := removeBitAndShift(number, position)

    fmt.Println()
    fmt.Println("Number after removing bit", position, "and shifting remaining bits:")
    printBinary(result)

    fmt.Println()
    fmt.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 Jun 24 by avibootz
edited Jun 24 by avibootz

Related questions

...