Created
May 13, 2018 06:11
-
-
Save braxtone/37df8caeddbfad8e207d24416e9fb05c to your computer and use it in GitHub Desktop.
Calculate bit flips for random integers, an adventure in Python's bitwise operators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
if len(sys.argv) != 2: | |
print("Usage: %s <number>" % sys.argv[0]) | |
sys.exit(1) | |
def flip_bit(number, n): | |
mask = (0b1 << (n-1)) | |
result = number ^ mask | |
return bin(result) | |
to_flip = int(sys.argv[1]) | |
print("Finding bit flips for:") | |
print("%s - %s" % (bin(to_flip), to_flip)) | |
length = len(bin(to_flip)) - 2 | |
print("Bit flips:") | |
for n in range(1, length): | |
flipped = flip_bit(to_flip, n) | |
print("%s - %s" % (flipped, int(flipped, 2))) | |
# $ ./bit_flips.py 22 | |
# Finding bit flips for: | |
# 0b10110 - 22 | |
# Bit flips: | |
# 0b10111 - 23 | |
# 0b10100 - 20 | |
# 0b10010 - 18 | |
# 0b11110 - 30 | |
# $ ./bit_flips.py 80 | |
# Finding bit flips for: | |
# 0b1010000 - 80 | |
# Bit flips: | |
# 0b1010001 - 81 | |
# 0b1010010 - 82 | |
# 0b1010100 - 84 | |
# 0b1011000 - 88 | |
# 0b1000000 - 64 | |
# 0b1110000 - 112 | |
# $ ./bit_flips.py 443 | |
# Finding bit flips for: | |
# 0b110111011 - 443 | |
# Bit flips: | |
# 0b110111010 - 442 | |
# 0b110111001 - 441 | |
# 0b110111111 - 447 | |
# 0b110110011 - 435 | |
# 0b110101011 - 427 | |
# 0b110011011 - 411 | |
# 0b111111011 - 507 | |
# 0b100111011 - 315 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment