Search code examples
arraysswiftbit-shift

Swift Bitshift Integers in Array to the Right


I've found a similar example in Python.

Essentially, say you have an array which is [1, 2, 3], and in binary that would be [0b00000001, 0b00000010, 0b00000011], what's the fastest way to bitshift that into [0b00000000, 0b10000001, 0b00000001]?

Basically bitshifting an array as if it were one huge int. (The left-hand side can always be assumed to be 0.)

Unfortunately I haven't got any code, because I have no clue how to achieve this, sorry!


Solution

  • I think you could do it something like this:

    func bitShift(array: [UInt8]) -> [UInt8] {
      var output = array
    
      var prevParity = false
    
      for i in 0..<output.count {
        // check parity of current value and store it
        let tempParity = (output[i] & 1) == 1
    
        // bitshift the current value to the right
        output[i] = output[i] >> 1
    
        if prevParity {
          // add on the first one if the previous value was odd
          output[i] = output[i] | 0b10000000
        }
    
        // store tempParity into prevParity for next loop
        prevParity = tempParity
      }
    
      return output
    }
    

    Advanced operators... https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html