Skip to content

Commit 07720bb

Browse files
committed
Functions that do bit operations.
1 parent b57990d commit 07720bb

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

bit_manipulation/bits.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,60 @@ def hamming_distance(x, y):
99
return count
1010

1111

12+
def hamming_weight(x):
13+
count = 0
14+
while x != 0:
15+
count += 1
16+
x &= x - 1
17+
return count
18+
19+
20+
def is_bit_set(bitfield, pos):
21+
return (bitfield & (1 << pos)) != 0
22+
23+
24+
def is_even(x):
25+
return x & 1 == 0
26+
27+
28+
def is_power_of_2(x):
29+
return (x & x - 1) == 0
30+
31+
32+
# Returns the n bits in bitfield starting at position pos
33+
def get_bits(bitfield, pos, n):
34+
return (bitfield >> (pos + 1 - n)) & ~(~0 << n)
35+
36+
1237
def main():
1338
# for x in range(0, 20):
1439
# print(x, bin(x), hex(x))
1540

1641
print("Hamming distance: 1010111100 and 1001010101: ", hamming_distance(0b1010111100, 0b1001010101))
1742

43+
print("Bit 0: 1011 1100 set?", is_bit_set(0b10111100, 0))
44+
print("Bit 1: 1011 1100 set?", is_bit_set(0b10111100, 1))
45+
print("Bit 2: 1011 1100 set?", is_bit_set(0b10111100, 2))
46+
print("Bit 3: 1011 1100 set?", is_bit_set(0b10111100, 3))
47+
print("Bit 4: 1011 1100 set?", is_bit_set(0b10111100, 4))
48+
print("Bit 5: 1011 1100 set?", is_bit_set(0b10111100, 5))
49+
print("Bit 6: 1011 1100 set?", is_bit_set(0b10111100, 6))
50+
print("Bit 7: 1011 1100 set?", is_bit_set(0b10111100, 7))
51+
52+
print("Hamming weight: 1010111100:", hamming_weight(0b1010111100))
53+
print("Hamming weight: 1001000001:", hamming_weight(0b1001000001))
54+
print("Hamming weight: 0001000000:", hamming_weight(0b0001000000))
55+
print("Hamming weight: 0000000000:", hamming_weight(0b0000000000))
56+
print("Hamming weight: 11111111:", hamming_weight(0b11111111))
57+
58+
for x in range(0, 5):
59+
print(str(x) + " is even?", is_even(x))
60+
61+
for x in range(0, 17):
62+
print(str(x) + " is power of 2?", is_power_of_2(x))
63+
64+
print("Get 3 bits starting at position 5 in 1010111100", bin(get_bits(0b1010111100, 5, 3)))
65+
print("Get 3 bits starting at position 8 in 1010111100", bin(get_bits(0b1010111100, 9, 3)))
1866

1967
if __name__ == "__main__":
2068
main()

0 commit comments

Comments
 (0)