Skip to content

Instantly share code, notes, and snippets.

@mdalp
Last active June 14, 2017 12:39
Show Gist options
  • Save mdalp/13fc9710e4a4826eb7e902bdf878c310 to your computer and use it in GitHub Desktop.
Save mdalp/13fc9710e4a4826eb7e902bdf878c310 to your computer and use it in GitHub Desktop.
Easy implementation of a conversion tool from integer to binary.
from __future__ import division
def binary_digits(n):
if n == 0:
return '0'
res = ''
while n > 0:
mod_n = n % 2
res = str(mod_n) + res
n = int(n / 2)
return res
assert binary_digits(0) == '0'
assert binary_digits(1) == '1'
assert binary_digits(2) == '10'
assert binary_digits(15) == '1111'
assert binary_digits(42) == '101010'
assert binary_digits(64) == '1000000'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment