Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String of text to unique integer method?

Is there a method that converts a string of text such as 'you' to a number other than

y = tuple('you')
for k in y:
  k = ord(k)

which only converts one character at a time?

like image 312
mikeLundquist Avatar asked Nov 29 '22 14:11

mikeLundquist


1 Answers

In order to convert a string to a number (and the reverse), you should first always work with bytes. Since you are using Python 3, strings are actually Unicode strings and as such may contain characters that have a ord() value higher than 255. bytes however just have a single byte per character; so you should always convert between those two types first.

So basically, you are looking for a way to convert a bytes string (which is basically a list of bytes, a list of numbers 0–255) into a single number, and the inverse. You can use int.to_bytes and int.from_bytes for that:

import math
def convertToNumber (s):
    return int.from_bytes(s.encode(), 'little')

def convertFromNumber (n):
    return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()
>>> convertToNumber('foo bar baz')
147948829660780569073512294
>>> x = _
>>> convertFromNumber(x)
'foo bar baz'
like image 67
poke Avatar answered Dec 05 '22 14:12

poke