해시 함수 구현해보기

마현우·2024년 4월 30일

1차 구현

로직 생각해보기

  1. 입력한 문자열을 한 글자씩 유니코드로 변환하기
  2. 각 변환된 유니코드를 비트시프트 연산하기
    • 3칸씩 오른쪽으로 시프트 연산하고 짤린 부분을 반대편에 붙이는 방식
  3. 변환된 리스트 형태의 결과를 join으로 이어 붙이기

내가 생각하는 문제점 또는 보완해야 할 점

  • 결과가 숫자로만 이루어져 있다
  • 결과값의 길이가 정해져 있지 않다
  • 글자마다 유니코드로 변환해주는 정도로 했기 때문에 계산을 좀 더 복잡하게 해야할 것 같다
def encode(ans):
    return [rotate_bits_right(ord(x), 3, 8) for x in ans]

def to_string(v):
    return ''.join([str(i) for i in v])

def rotate_bits_right(number, shift, bit_length):
    rotated_bits = number >> shift & ((1 << bit_length) - 1)
    result = (number << (bit_length - shift)) | rotated_bits
    return result
        

ans = input()
encode_value = encode(ans)
result = to_string(encode_value)

print(result)

2차 수정

일단 간단하게 인코딩할 때 유니코드로 변환한 데이터를 제곱하고 10을 나눈 나머지를 시프트 연산하도록 했다

def encode(ans):
    return [rotate_bits_right(ord(x)**2%10, 3, 8) for x in ans]

def to_string(v):
    return ''.join([str(i) for i in v])

def rotate_bits_right(number, shift, bit_length):
    rotated_bits = number >> shift & ((1 << bit_length) - 1)
    result = (number << (bit_length - shift)) | rotated_bits
    return result
        

ans = input()
encode_value = encode(ans)
result = to_string(encode_value)

print(result)

0개의 댓글