Skip to content

Instantly share code, notes, and snippets.

@nebil
Last active February 11, 2020 11:20
Show Gist options
  • Save nebil/b0cee3e049b0afd4722b948d3e013ff6 to your computer and use it in GitHub Desktop.
Save nebil/b0cee3e049b0afd4722b948d3e013ff6 to your computer and use it in GitHub Desktop.
🔟 barrtodec -- turn a bitmap into a decimal integer using Python
"""
barrtodec.py -- turn a bitmap into a decimal integer using Python
This source code is licensed under a Creative Commons CC0 license.
More info at <https://creativecommons.org/publicdomain/zero/1.0/>.
"""
from functools import reduce
def barrtodec(bitarray):
bits = "".join(str(bit) for bit in bitarray)
return int(bits, 2)
def barrtodec2(bitarray):
# This reduce-based approach should improve the performance,
# since it doesn’t convert each and every bit into a string.
return reduce(lambda array, bit: array << 1 | bit, bitarray)
if __name__ == "__main__":
example = [1, 1, 1, 1, 1, 0]
decimal = barrtodec(example)
print(decimal)
assert decimal == 62
another_example = [1, 1, 0, 1, 1, 0, 0, 0, 1]
another_decimal = barrtodec2(another_example)
print(another_decimal)
assert another_decimal == 433
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment