How would I generate unique 16 digit alphanumeric based on input number in python. Result should be the same if we run the function multiple times. for example if the input is 100 and the program returns 12345678abcdefgh and next time if the user provides same input it should return the same result 12345678abcdefgh.
CodePudding user response:
You could use the hashlib module to hash the input integer. The generated hash will always be the same if the input is the same.
import hashlib
print('Enter a number to hash: ')
to_hash = input()
digest_32 = hashlib.md5(bytes(int(to_hash))).hexdigest()
digest_16 = digest_32[0:16]
# output: 6d0bb00954ceb7fbee436bb55a8397a9
print(digest_32)
# output: 6d0bb00954ceb7fb
print(digest_16)
CodePudding user response:
"""
generate unique 16 digit alphanumeric based on input number in python. Result
should be the same if we run the function multiple times. for example if
the input is 100 and the program returns 12345678abcdefgh and next time if the
user provides same input it should return the same result 12345678abcdefgh.
"""
# Note: This does not use hashlib because hash returns HEX values which
# are 16 alphanumeric characters:
# 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
def generate_alphanumeric(number):
# Convert the number to binary representation
binary = bin(number)
# remove 0b from binary representation prefix
mask_right_side = binary[2:]
# Create a mask to select 16 characters based on the binary representation.
# Creating padding 0's for the mask_left_side
mask_left_side = '0' * (16 - len(mask_right_side)) # Padding characters
# Create the 16 character mask
mask = mask_left_side mask_right_side
# Create a list of tuples of (zero_code, one_code)
zeros_codes = '12345678apqdexgh'
ones_codes = '90ijklmnobcrsfyz'
codes = list(zip(zeros_codes, ones_codes))
# Create the alphanumeric output.
if len(mask) <= 16:
result = ''
for index in range(16):
value = int(mask[index])
zero_code, one_code = codes[index]
if value: # mask value is 1
result = one_code
else:
result = zero_code
return result
else:
message = f'The entered values {number:,d} is greater that 65,' \
f'535. This is not allowed because the returned 16 ' \
f'character alphanumberic text will be a repeat of text ' \
f'assigned in the range of 0 to 65,535. This violates the ' \
f'requirement for unique text per number.'
return message
# Testing
print(generate_alphanumeric(100))
print(generate_alphanumeric(15))
print(generate_alphanumeric(0))
print(generate_alphanumeric(65_535))
print(generate_alphanumeric(65_536))