Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Reversibly encode alphanumeric string to integer

I want to convert a string (composed of alphanumeric characters) into an integer and then convert this integer back into a string:

string --> int --> string

In other words, I want to represent an alphanumeric string by an integer.

I found a working solution, which I included in the answer, but I do not think it is the best solution, and I am interested in other ideas/methods.

Please don't tag this as duplicate just because a lot of similar questions already exist, I specifically want an easy way of transforming a string into an integer and vice versa.

This should work for strings that contain alphanumeric characters, i.e. strings containing numbers and letters.

like image 439
charelf Avatar asked Nov 21 '18 21:11

charelf


People also ask

How do I encode strings to integers in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

Why do we use encode () in Python?

What does encode() do in Python? In today's world, security is critical in many applications. As a result, secure information storage in the database is required, and encoded copies of strings must be saved. To achieve this encoding process, Python encode() function is used.

How do I convert a string to an int?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

How do I convert a string to a return in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.


2 Answers

Here's what I have so far:

string --> bytes

mBytes = m.encode("utf-8")

bytes --> int

mInt = int.from_bytes(mBytes, byteorder="big")

int --> bytes

mBytes = mInt.to_bytes(((mInt.bit_length() + 7) // 8), byteorder="big")

bytes --> string

m = mBytes.decode("utf-8")

try it out:

m = "test123"
mBytes = m.encode("utf-8")
mInt = int.from_bytes(mBytes, byteorder="big")
mBytes2 = mInt.to_bytes(((mInt.bit_length() + 7) // 8), byteorder="big")
m2 = mBytes2.decode("utf-8")
print(m == m2)

Here is an identical reusable version of the above:

class BytesIntEncoder:

    @staticmethod
    def encode(b: bytes) -> int:
        return int.from_bytes(b, byteorder='big')

    @staticmethod
    def decode(i: int) -> bytes:
        return i.to_bytes(((i.bit_length() + 7) // 8), byteorder='big')

If you're using Python <3.6, remove the optional type annotations.

Test:

>>> s = 'Test123'
>>> b = s.encode()
>>> b
b'Test123'

>>> BytesIntEncoder.encode(b)
23755444588720691
>>> BytesIntEncoder.decode(_)
b'Test123'
>>> _.decode()
'Test123'
like image 64
charelf Avatar answered Oct 31 '22 18:10

charelf


Recall that a string can be encoded to bytes, which can then be encoded to an integer. The encodings can then be reversed to get the bytes followed by the original string.

This encoder uses binascii to produce an identical integer encoding to the one in the answer by charel-f. I believe it to be identical because I extensively tested it.

Credit: this answer.

from binascii import hexlify, unhexlify

class BytesIntEncoder:

    @staticmethod
    def encode(b: bytes) -> int:
        return int(hexlify(b), 16) if b != b'' else 0

    @staticmethod
    def decode(i: int) -> int:
        return unhexlify('%x' % i) if i != 0 else b''

If you're using Python <3.6, remove the optional type annotations.

Quick test:

>>> s = 'Test123'
>>> b = s.encode()
>>> b
b'Test123'

>>> BytesIntEncoder.encode(b)
23755444588720691
>>> BytesIntEncoder.decode(_)
b'Test123'
>>> _.decode()
'Test123'
like image 20
Asclepius Avatar answered Oct 31 '22 17:10

Asclepius