Skip to content

Instantly share code, notes, and snippets.

@jpf
Created August 27, 2018 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpf/a9a6a027edd850e34dee14d1f52f930a to your computer and use it in GitHub Desktop.
Save jpf/a9a6a027edd850e34dee14d1f52f930a to your computer and use it in GitHub Desktop.
Counts the number of "1" and "0" bits in an input file
#!/usr/bin/env python3
# Counts the number of "1" and "0" bits in an input file
import sys
bits_per_byte = 8
# Via: https://stackoverflow.com/a/1035456
def bytes_from_file(filename, chunksize=8192):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
for b in chunk:
yield b
else:
break
def count_ones(byte):
bits = format(b, "0{}b".format(bits_per_byte))
return len(list(filter(lambda x: x == "1", list(bits))))
filename = sys.argv[1]
ones_found = 0
zeros_found = 0
for b in bytes_from_file(filename):
ones = count_ones(b)
ones_found += ones
zeros_found += bits_per_byte - ones
total_bits = ones_found + zeros_found
print(filename)
print("Total bits counted: {0}\nOnes: {1} ({2:.3f})\nZeros: {3} ({4:.3f})\n".format(
total_bits,
ones_found,
ones_found / total_bits,
zeros_found,
zeros_found / total_bits))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment