How to Generate Random 64-Bit Value as Decimal String in PHP

How to generate random 64-bit value as decimal string in PHP

You could use two 32-bit numbers, four 16-bit numbers, etc.

PHP has rand() and and mt_rand() but how many random bits they supply isn't specified by the standard (though they can be queried with the help of getrandmax() and mt_getrandmax(), respectively.)

So your safest simplest bet would be generating 64 random bits and setting them one by one.

As for working with 64-bit integers, I'd recommend using the GMP library as it has a good range of functions to help you out.

You could create a number, call 64 gmp_setbit()s on it with successive positions then convert it to a string using gmp_strval().

Turning an integer into random string and back again

Ok, one of the ideas is to use a character array as a representation of a numeric system. Then you can convert from base 10 to base x and vica-versa. The value will be shorter and less readable (altought, you should encrypt it with a two-way crypter if it must be secure).

A solution:

final class UrlShortener {

private static $charfeed = Array(
'a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m',
'M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w','W','x','X','y','Y',
'z','Z','0','1','2','3','4','5','6','7','8','9');

public static function intToShort($number) {
$need = count(self::$charfeed);
$s = '';

do {
$s .= self::$charfeed[$number%$need];
$number = floor($number/$need);
} while($number > 0);

return $s;
}

public static function shortToInt($string) {
$num = 0;
$need = count(self::$charfeed);
$length = strlen($string);

for($x = 0; $x < $length; $x++) {
$key = array_search($string[$x], self::$charfeed);
$value = $key * pow($need, $x);
$num += $value;
}

return $num;
}
}

Then you can use:

UrlShortener::intToShort(2);
UrlShortener::shortToInt("b");

EDIT

with large numbers, it does not work. You should use this version (with bcmath http://www.php.net/manual/en/book.bc.php ) with very large numbers:

final class UrlShortener {

private static $charfeed = Array(
'a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m',
'M','n','N','o','O','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w','W','x','X','y','Y',
'z','Z','0','1','2','3','4','5','6','7','8','9');

public static function intToShort($number) {
$need = count(self::$charfeed);
$s = '';

do {
$s .= self::$charfeed[bcmod($number, $need)];
$number = floor($number/$need);
} while($number > 0);

return $s;
}

public static function shortToInt($string) {
$num = 0;
$need = count(self::$charfeed);
$length = strlen($string);

for($x = 0; $x < $length; $x++) {
$key = array_search($string[$x], self::$charfeed);
$value = $key * bcpow($need, $x);
$num += $value;
}

return $num;
}
}
$original = 131569877435989900;
$short = UrlShortener::intToShort($original);
echo $short;
echo '<br/>';
$result = UrlShortener::shortToInt($short);
echo $result;
echo '<br/>';
echo bccomp($original, $result);

If something missing from here, please let me know, because it's only a snippet from my library (I don't wanna insert the whole thing here)

negra

Random Float between 0 and 1 in PHP

You may use the standard function: lcg_value().

Here's another function given on the rand() docs:

// auxiliary function
// returns random number with flat distribution from 0 to 1
function random_0_1()
{
return (float)rand() / (float)getrandmax();
}

Random variable length bigint(8) number using PHP?

Short answer, gmp_random_range():

$from = 0;
$to = '18446744073709551615';
$random = gmp_random_range($from, $to);
var_dump($random, (string)$random);

E.g.:

object(GMP)#1 (1) {
["num"]=>
string(20) "10366718409313808674"
}
string(20) "10366718409313808674"

Additional digressions:

  • MySQL's BIGINT is an 8-byte integer, what means -263 to 263-1 if signed and 0 to 264-1 if unsigned.

  • PHP_INT_MAX is a 4-byte value in 32-bit builds but an 8-byte value in 64-bit builds. It's signed in either case.

So if you could safely assume 64-bit PHP and you wanted signed numbers then you'd be basically done with any random generation function. You could use random_int() if you're after cryptographically secure numbers or mt_rand() otherwise:

var_dump(random_int(0, PHP_INT_MAX));
var_dump(mt_rand(0, PHP_INT_MAX));

But you want unsigned values, thus you must switch to strings. Once there, an obvious approach is to generate two integers and concatenate them as strings—the tricky part is ensuring you don't overflow your range. As alternative, you can use the GMP arbitrary precision extension, which happily has a dedicated function.

P.S. You actually mention BIGINT(8). That 8 is nothing but the display size when printing from compliant clients, it doesn't represent the storage range and it isn't enforced by any mean. And since you clearly state you expect up to 20 digits, it's just misleading.

Generator for random long hex strings in PHP

While this answers OP's question, if what you are looking for is random, then @danorton answer may be a better fit.


Like this:

$val = '';
for( $i=0; $i<100; $i++ ) {
$val .= chr(rand(65, 90));
}

65 is A while 90 is Z. if you do not like "magic numbers" this form may be more readable:

$val = '';
for( $i=0; $i<100; $i++ ) {
$val .= chr(rand(ord('A'), ord('Z')));
}

I'd make ord() result a variable and move it out of the loop though for performance reasons:

$A = ord('A');
$Z = ord('Z');
$val = '';
for( $i=0; $i<100; $i++ ) {
$val .= chr(rand($A, $Z));
}

Or you could glue output of sha1()s (three of them) and cut down to 100 chars. Or use md5() instead (but I'd stick to sha1()).

EDIT sha1() outputs 40 chars long string, md5() 32 chars long. So if you do not want to glue char by char (as in loop I gave above) try this function

function getId($val_length) {
$result = '';
$module_length = 40; // we use sha1, so module is 40 chars
$steps = round(($val_length/$module_length) + 0.5);

for( $i=0; $i<$steps; $i++ ) {
$result .= sha1(uniqid() . md5(rand());
}

return substr($result, 0, $val_length);
}

where function argument is length of string to be returned. Call it getId(100);

Generate a 64-bit number (as a hex string)

Do you mean something like this?

$id = bin2hex(openssl_random_pseudo_bytes(8));

It generates a hex representation of a 64 bit random number.

Auto-generate Base62 numbers without vowels (PHP)?

There's a function in an answer of mine here that can convert from any base to any other and which lets you customize the digit pool; it also works on arbitrary-sized input. You can generate a sequence in base 10 and convert to whatever you need.

Generating a natural number ouf of PHP's lcg_value()?

either type float or int are bounded by platform

Integer The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.


float The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

to maintain highest precision of float, u can refer http://www.php.net/manual/en/function.bcmul.php



Related Topics



Leave a reply



Submit