Skip to content

Instantly share code, notes, and snippets.

@Narsil
Created March 30, 2023 08:56
Show Gist options
  • Save Narsil/6dd3c14a0819f6b35c51c4c4ec085bf7 to your computer and use it in GitHub Desktop.
Save Narsil/6dd3c14a0819f6b35c51c4c4ec085bf7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""Toggle the bit at the specified offset.
Syntax: <cmdname> filename bit-offset"""
import sys
import os
import random
fname = sys.argv[1]
# Convert bit offset to bytes + leftover bits
file_stats = os.stat(fname)
total_bytes = file_stats.st_size
total_bits = total_bytes * 8
target_bit = random.randrange(total_bits)
nbytes = target_bit // 8
nbits = target_bit % 8
# Open in read+write, binary mode; read 1 byte
fp = open(fname, "r+b")
fp.seek(nbytes, 0)
c = fp.read(1)
# Toggle bit at byte position `nbits`
toggled = bytes([ord(c) ^ (1 << nbits)])
# print(toggled) # diagnostic output
# Back up one byte, write out the modified byte
fp.seek(-1, 1) # or absolute: fp.seek(nbytes, 0)
fp.write(toggled)
fp.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment