Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # turn hex values into decimals
- # and vise versa
- def hex_code(value, mode):
- # dictionary containing
- # hexadecimal equivalents
- # of decimals
- hex_dict = {
- 10:'A',
- 11:'B',
- 12:'C',
- 13:'D',
- 14:'E',
- 15:'F'
- }
- # if turning hex values
- # into decimals, reverse
- # the dictionary
- if mode == 'decode':
- hex_dict = {v:k for k,v in hex_dict.items()}
- # list the values so
- # we can change their
- # properties
- value = list(value)
- for i in range(len(value)):
- # store the current value
- # so indexing will be easier
- # to read
- item = value[i]
- if not(item in hex_dict):
- continue
- value[i] = hex_dict[item]
- return value
- # any number base to decimal
- def any_to_decimal(value, from_base):
- # if value is in base 16,
- # convert the values to
- # decimal equivalent
- value = hex_code(value, 'decode')
- # variables to store
- # the output and the
- # exponent
- output = 0
- expo = 0
- # iterate through the
- # value in reverse
- for i in value[::-1]:
- output += int(i) * (from_base ** expo)
- expo += 1
- return output
- # decimal to any number base
- def decimal_to_any(value, to_base):
- # list variable to
- # store the remainders
- output = []
- # append the remainders
- # to output until value reaches 0
- while value > 0:
- output.append(value % to_base)
- value //= to_base
- # convert values to hex
- # equivalents if to_base == 16
- if to_base == 16:
- output = hex_code(output, 'encode')
- # reverse the output
- output = output[::-1]
- return output
- # octal to hexadecimal vise versa
- def octal_to_hexa(value, from_base):
- # turn the value into
- # decimal so we can
- # convert the decimal into
- # the other base
- output = any_to_decimal(value, from_base)
- # convert the value again to the opposite base
- if from_base == 8:
- output = decimal_to_any(output, 16)
- else:
- output = decimal_to_any(output, 8)
- return output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement