Created
April 14, 2017 20:19
-
-
Save imdanielsp/ff00c7afd00e3660c6961ff96d982fef to your computer and use it in GitHub Desktop.
Base 2 and Base 10 Converter Script Using Local Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def converter(number, base): | |
def convert_to_base_10(val): | |
target_base = 10 # Target number base | |
output_sum = 0 # Initial value for output sum | |
expo = 0 # Initial exponent | |
digits = [int(x) for x in str(val)] # Convert the base 2 number to an array of integer | |
digits.reverse() # Reverse the array. | |
for d in digits: # For each bit... | |
if d != 0: # If it's not 0, we will get the value relative to the position | |
output_sum += pow(2, expo) # Add it to the output | |
expo += 1 # Move to the next bit | |
return output_sum, target_base | |
def convert_to_base_2(val): | |
target_base = 2 # Target number base | |
binary = [] | |
while True: | |
reminder = val % target_base | |
val = int(val / target_base) # Force int truncation | |
binary.append(reminder) # Put the digit in the list | |
if val > 0: | |
continue # We still need to divide | |
else: | |
break # Nothing else to do | |
binary.reverse() | |
binary = list(map(lambda x: str(x), binary)) # Transform the int to an array of str | |
return int(''.join(binary)), target_base | |
if base == 2: | |
return convert_to_base_10(number) | |
elif base == 10: | |
return convert_to_base_2(number) | |
if __name__ == '__main__': | |
print("Converting from binary to decimal") | |
print(converter(101110011, 2)) | |
print("Converting from decimal to binary") | |
print(converter(708, 10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment