Skip to content

Instantly share code, notes, and snippets.

@brpowell
Created April 26, 2015 05:21
Show Gist options
  • Save brpowell/855008b624e73421e649 to your computer and use it in GitHub Desktop.
Save brpowell/855008b624e73421e649 to your computer and use it in GitHub Desktop.
Manipulating hex numbers
#
# Takes a hexidecimal number, converts it to every base between 2 and 15,
# and concatenates the result for each to a super_string. Starts at 16 and
# converts through to base-2.
#
# e.g. 0x52 --> 52575c646a75821011221452143121102100011010010
#
# Count the occurances of each character, and create a new string. The string
# contains each unique character ordered by number of occurances first, then
# ordered by value highest to lowest.
#
# e.g. 52575c646a75821011221452143121102100011010010 --> 1025476ca83
""" Converts decimal number to base-b """
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and "0" ) or ( baseN(num // b, b).lstrip("0") + numerals[num % b])
# Get input in hex, convert to decimal
while(1):
try:
num_hex = raw_input("Enter hex number: 0x")
num_dec = int(num_hex, 16)
break
except ValueError:
print('Invalid hexadecimal character')
super_string = num_hex
final_string = ''
char_list = {}
# Convert num_dec to different bases, add to super_string
n = 15
while(n >= 2):
super_string += baseN(num_dec, n)
n -= 1
# (hex character, ocurrances) initialize occurances to 0
for c in super_string:
char_list[c] = (int(c, 16), 0)
# (hex character, ocurrances+1) Add 1 for every time char appears in string
for c in super_string:
char_list[c] = (char_list[c][0], char_list[c][1]+1)
# Arrange characters accordingly and add to final string
for k in range(0, len(char_list)):
max_tuple = (0, 0)
for entry in char_list:
entry_tuple = char_list[entry]
if(entry_tuple[1] > max_tuple[1]):
max_tuple = entry_tuple
lead = entry
elif(entry_tuple[1] == max_tuple[1]):
if(entry_tuple[0] > max_tuple[0]):
max_tuple = entry_tuple
lead = entry
del char_list[lead]
final_string += lead
print('0x' + num_hex + ' ---> ' + final_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment