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

1 Answer

0 votes
import Foundation

/*
    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
    */

    let left  = number >> (position + 1)              // bits above removed bit
    let 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:
            String(value, radix: 2) → binary string
            left-padding to 32 bits
            grouping into 4-bit chunks for readability
    */

    var binary = String(value, radix: 2)
    if binary.count < 32 {
        binary = String(repeating: "0", count: 32 - binary.count) + binary
    }

    let grouped = stride(from: 0, to: 32, by: 4)
        .map { i in
            let start = binary.index(binary.startIndex, offsetBy: i)
            let end = binary.index(start, offsetBy: 4)
            return String(binary[start..<end])
        }
        .joined(separator: " ")

    print(grouped)
}

// Main program
let number: Int = 22
let position: Int = 2   // remove bit 2 (0 = LSB)

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

let result: Int = removeBitAndShift(number, position)

print("\nNumber after removing bit \(position) and shifting remaining bits:")
printBinary(result)

print("\nResult 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

...