Skip to content

Instantly share code, notes, and snippets.

@gquittet
Created March 13, 2017 11:08
Show Gist options
  • Save gquittet/58d6c5ccb6bc74452f2ef0785a8d1a80 to your computer and use it in GitHub Desktop.
Save gquittet/58d6c5ccb6bc74452f2ef0785a8d1a80 to your computer and use it in GitHub Desktop.
Conversion: Decimal to Binary and Binary to Decimal
# -*- coding: utf-8 -*-
def decimalToBinary(n):
""" Return the binary representation
of an Integer
:param n An Integer
:return A binary
"""
if (n < 0):
raise ValueError('The Integer n must be >= 0')
result = ''
while (n >= 1):
result = str(n % 2) + result
n = int(n / 2)
return int(result)
def binaryToDecimal(n):
""" Return the integer representation
of an binary
:param n A binary
:return An Integer
"""
if (n < 0):
raise ValueError('The Integer n must be >= 0')
result = 0
string = str(n)
for i in range(0, len(string)):
result += int(string[i]) * 2 ** (len(string) - 1 - i)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment