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

1 Answer

0 votes
import Foundation

/*
    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.
*/
func removeBitsAndShift(number: Int, positions: [Int]) -> Int {

    // Sort positions descending
    let sorted: [Int] = positions.sorted(by: >)

    var result: Int = number

    for pos: Int in sorted {
        let left: Int  = result >> (pos + 1)          // bits above removed bit
        let right: Int = result & ((1 << pos) - 1)    // bits below removed bit

        result = (left << pos) | right                // merge
    }

    return result
}

/*
    printBinary(n)
    --------------
    Prints a 32-bit binary representation of an integer.
*/
func printBinary(_ n: Int) {
    let binary: String = String(n, radix: 2).leftPadding(toLength: 32, withPad: "0")
    let grouped: String = 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)
}

// Helper extension for padding
extension String {
    func leftPadding(toLength: Int, withPad: String) -> String {
        if self.count >= toLength { return self }
        return String(repeating: withPad, count: toLength - self.count) + self
    }
}

// Main program
let number: Int = 1234                 // 0000 0000 0000 0000 0000 0100 1101 0010
let positions: [Int] = [1, 3, 7]       // remove bits 1, 3, 7 (0 = LSB)

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

let result: Int = removeBitsAndShift(number: number, positions: positions)

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

print("\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 2 days ago by avibootz

Related questions

...