Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting a '0' bit into the middle of a bitsequence in python

This should be fairly simple, but I’ve yet to see a viable solution.

If I have a bit sequence (represented as an integer), how would I insert a 0 at index n?

For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

insert(0b100101010101,4) -> 0b1001001010101

insert(0b101,3) -> 0b1010

insert(0b10001,2) -> 0b100001

EDIT: To clarify, I would like to do this without using vectors or strings (only bitwise operators)

>Solution :

You would need to isolate the bits to the left and to the right of the insertion point, then shift the left part one position, and combine both parts again:

def insert(n, bit):
    length = n.bit_length()
    if bit > length:
        raise ValueError("argument out of range")
    right = n & ((1 << length - bit) - 1)
    return ((n - right) << 1) + right
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading