Skip to content

Instantly share code, notes, and snippets.

@clee704
Last active August 29, 2015 14:07
Show Gist options
  • Save clee704/05055a993083545a64e5 to your computer and use it in GitHub Desktop.
Save clee704/05055a993083545a64e5 to your computer and use it in GitHub Desktop.
Randomly flip bits in the file
#! /usr/bin/env python
# Randomly flip bits in the file.
import argparse
import random
parser = argparse.ArgumentParser()
parser.add_argument('file', help='the file whose bits to be fliped')
parser.add_argument('count', type=int, default=1, nargs='?', help='number of rounds of bit flipping (default: 1)')
args = parser.parse_args()
with open(args.file, 'rb+') as f:
f.seek(0, 2)
n = f.tell()
for _ in range(args.count):
k = random.randint(0, n - 1)
f.seek(k, 0)
byte = ord(f.read(1))
f.seek(-1, 1)
x = 1 << random.randint(0, 7)
f.write(chr(byte ^ x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment