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

Easiest way to turn kth bit from right to zero in python 3

I have to change kth bit from right to 0. If it is already 0 I do not have to change anything.

For n = 37 and k = 3, the output should be 33.

37 = 100101 ~> 100001 = 33

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

For n = 37 and k = 4, the output should be 37. Since the bit is already 0.

I have seen a couple of answers on SO but, I was not able to figure out.

How to modify bits in an integer?

how to change 1 to 0 and 0 to 1 in binary(Python)

Python – Flipping Binary 1's and 0's in a String

>Solution :

use <<(shift left), & (bitwise and operator) and ~ (bitwise not operator) to achieve this

import sys

def changeBit(val,bit):
    flip = 1<<(bit-1)
    val = ~(flip) & val
    return val

print(changeBit(37,3))
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