Search code examples
iosbit-fields

How to perform an insertion operation on a bit field?


How do I do an insertion operation on a bit field?

If I have 1111 (integer 15) how can I insert a 0 at "index" 1 to get 11101?

I'm writing in Swift 4 and I'm using Int as the data type.

In this Stackoverflow post they show how to perform a removal operation on a bitfield (it's in java but this is fairly language agnostic): Removing bit at specific index

P.S. This is high performance code.


Solution

  • You need to extract the bits below the insertion point, and the bits above. You need to shift-left the bits above, then recombine the parts. Thus:

    var x: UInt64 = 0b1111
    let index: UInt64 = 1
    let lowMask: UInt64 = (1 << index) - 1
    let highMask: UInt64 = ~lowMask
    x = ((x & highMask) << 1) | (x & lowMask)
    print(String(x, radix: 2))
    // Output: 11101