Create a unique 4-byte integer from a string in PHP

I have an SQL table that uses rows for a key. I need to convert this string (maximum 18 characters) to a unique (!) 4-byte integer using PHP. Can anyone help?

+4
source share
3 answers

Unique? Impossible, sorry .

Let's take a closer look:

With 18 characters, even if we only accepted 128 possible ASCII characters (7 bits), you would get 128 ^ 18 possible lines (and I'm not even going to use shorter lines!), Which is about 8E37 (8 and 37 zeros) .

With a 4-byte integer, you get 256 ^ 4 possible integers, which is about 4E9 (4 billion).

So, you have 4E28 more lines than you have integers; You cannot have a unique mapping.

Therefore, you will certainly encounter a collision as soon as you enter the key 4294967297th, but you can run it as soon as you enter more than one.

See also: http://en.wikipedia.org/wiki/Pigeonhole_principle

+1
source

Store the string lookup table in integers. Each time you encounter a new row, you add it to the mapping table and assign it a new unique identifier. This will work for about 2 ^ 32 lines, which is probably enough.

There is no way to do this for more than 2 ^ 32 different lines.

0
source

You can not. A four-byte integer can represent 2 ^ 32 = 4 billion values, which is not enough to store the target space.

If the table currently has less than 4 billion rows, you can create a crosstab that simply assigns a step value to each one. This approach will be limited to 4 billion lines, but it may be good for your situation.

0
source

Source: https://habr.com/ru/post/1398659/


All Articles