Skip to content

Instantly share code, notes, and snippets.

@Solonarv
Created December 8, 2016 16:11
Show Gist options
  • Save Solonarv/ff38c600a1edc0a6ba8e4bad4ee4d1fd to your computer and use it in GitHub Desktop.
Save Solonarv/ff38c600a1edc0a6ba8e4bad4ee4d1fd to your computer and use it in GitHub Desktop.
#-*-coding:utf8;-*-
#qpy:3
#qpy:console
from random import randint
def bin(n, width):
return blockify(("{:0"+str(width)+"b}").format(n))
def blockify(s):
return '['+s.replace('0', ' ').replace('1', '#')+']'
width = 10
while True:
print("Enter a number to convert, r for a random number, e to exit, or wN to change width to N.")
i = raw_input("> ")
if i == '':
continue
elif i[0] == 'e':
break
elif i[0] == 'w':
try:
nw = int(i[1:])
except InvalidArgumentException:
nw = -1
if nw > 0:
width = nw
print("Width set to {}.".format(width))
else:
print("Please enter a positive integer.")
continue
elif i[0] == 'r':
n = randint(0, 2**width)
else:
try:
ni = int(i)
except InvalidArgumentException:
print("Please enter a valid integer.")
continue
n = ni % 2**width
print("Input: {}".format(n))
print("blockified:\n{}".format(bin(n, width)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment