For example, I have a number 255 that is 1111 1111 in binary form. I want to turn the first bit to 0 and get the 0111 1111 (127). What is the easiest way to do this? How I can change the bits of number directly?
Asked
Active
Viewed 1,128 times
0
-
3The more generic question and solution: http://stackoverflow.com/questions/12173774/modify-bits-in-an-integer-in-python – amito Sep 06 '15 at 07:36
1 Answers
5
a = 0b11111111 # = 255
mask = 0b01111111 # = 127
res = a & mask
print('{0} {0:08b}'.format(res))
# -> 127 01111111

hiro protagonist
- 44,693
- 14
- 86
- 111
-
-
-
-
1you mean the leading zero in the formatting string `08b`? that will just zero-fill the resulting string if the bitlength is shorter than 8. `'{0:03b}'.format(0) = 000`. – hiro protagonist Aug 19 '17 at 07:26