Skip to content

Instantly share code, notes, and snippets.

@mjdargen
Created November 3, 2020 23:42
Show Gist options
  • Save mjdargen/93e3fc6ebebda7870820d93454993684 to your computer and use it in GitHub Desktop.
Save mjdargen/93e3fc6ebebda7870820d93454993684 to your computer and use it in GitHub Desktop.
# ask for input
number = int(input("Please enter an 8-bit binary number: "))
# extract each bit
bit0 = number % 10
bit1 = number % 100 // 10
bit2 = number % 1000 // 100
bit3 = number % 10000 // 1000
bit4 = number % 100000 // 10000
bit5 = number % 1000000 // 100000
bit6 = number % 10000000 // 1000000
bit7 = number % 100000000 // 10000000
# multiply by a power of 2 and add to total
total = bit0 * 2 ** 0
total += bit1 * 2 ** 1
total += bit2 * 2 ** 2
total += bit3 * 2 ** 3
total += bit4 * 2 ** 4
total += bit5 * 2 ** 5
total += bit6 * 2 ** 6
total += bit7 * 2 ** 7
# print the result
print(f"{number} converts to {total} in base-10.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment