from math import log, floor def largest_power_of_base_less_than(base, number): return int(floor(log(number, base))) def to_binary(num): if num == 0: # Log_2(0) = -infinity. Python dislikes infinity. We need to return '0' largest_power = largest_power_of_base_less_than(2, num) # The largest integer <= log_2(num) current_power = largest_power # We're going to change this one in the loop digits = [] while current_power >= 0: if num >= (2 ** current_power): # a**b means a^b (python uses ^ for binary xor instead of this) digits.append('1') # This digit is a 1 num = num - (2 ** current_power) # Make the number smaller by the power of 2 we found else: digits.append('0') # The current power of 2 isn't in our number, so this digit is a zero current_power = current_power - 1 # Move to the next smallest power of 2 return ''.join(digits) # This turns the list into a string. For example, ['1', '0', '1'] => '101' def test(): for num in range(0, 10): binary_version = to_binary(num) print("%s is %s in binary" % (num, binary_version)) assert (num == int(binary_version, 2)) test()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question