dEN5

Create a hexadecimal colour based on a string with python

Dec 27th, 2021
1,174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. def FloatToHex(number, base = 16):
  2.     if number < 0:                          # Check if the number is negative to manage the sign
  3.         sign = "-"                          # Set the negative sign, it will be used later to generate the first element of the result list
  4.         number = -number                    # Change the number sign to positive
  5.     else:
  6.         sign = ""                           # Set the positive sign, it will be used later to generate the first element of the result list
  7.  
  8.     s = [sign + str(int(number)) + '.']     # Generate the list, the first element will be the integer part of the input number
  9.     number -= int(number)                   # Remove the integer part from the number
  10.  
  11.     for i in range(base):                   # Iterate N time where N is the required base
  12.         y = int(number * 16)                # Multiply the number by 16 and take the integer part
  13.         s.append(hex(y)[2:])                # Append to the list the hex value of y, the result is in format 0x00 so we take the value from postion 2 to the end
  14.         number = number * 16 - y            # Calculate the next number required for the conversion
  15.  
  16.     return ''.join(s).rstrip('0')
  17.  
  18. def charCodeAt(testS):
  19.     l = list(bytes(testS, 'utf-16'))[2:]
  20.     for i, c in enumerate([(b<<8)|a for a,b in list(zip(l,l[1:]))[::2]]):
  21.         return c
  22.  
  23.  
  24.  
  25. def stringToColour(text):
  26.     hash = 0
  27.     for x in text:
  28.         hash = charCodeAt(x) + ((hash << 5) - hash)
  29.  
  30.     colour = '#';
  31.     for i in range(3-1):
  32.         value = (hash >> (i * 8)) & 0xFF;
  33.         colour += ('00' + FloatToHex(value,16)[-2])
  34.     return colour
  35.  
  36.  
  37.  
  38. print(stringToColour('триллер'))
Advertisement
Add Comment
Please, Sign In to add comment