根据 python 中的输入数字生成唯一的 16 位字母数字

Generate unique 16 digit alphanumeric based on input number in python

我如何根据 python 中的输入数字生成唯一的 16 位字母数字。如果我们 运行 函数多次,结果应该是相同的。 例如,如果输入是 100 并且程序 returns 12345678abcdefgh 并且下一次如果用户提供相同的输入它应该 return 相同的结果 12345678abcdefgh.

您可以使用 hashlib 模块对输入整数进行哈希处理。如果输入相同,生成的哈希将始终相同。

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)
"""
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))