简体   繁体   中英

How to implement javascript int.toString(32) in PHP?

I have a uniqueId function that generates an unique ID of a string. I use this in javascript, you can find it here (see my answer): Generate unique number based on string input in Javascript

I want to do the same the same in PHP, but the function produces mostly floats instead of unsigned ints (beyond signed int value PHP_MAX_INT ) and because of that i cannot use the PHP function dechex() to convert it to hex. dechex() is limited to PHP_MAX_INT value so every value above the PHP_MAX_INT will be returned as FFFFFFFF .

In javascript instead, when using int.toString(32), it produces a string with other letters than A..F, for example:

dh8qi9t
je38ugg

How do I achieve the same result in PHP?

I would suggest base_convert($input,10,32) , but as you observed it won't work for numbers that are too big.

Instead, you could implement it yourself:

function big_base_convert($input,$from,$to) {
  $out = "";
  $alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
  while($input > 0) {
    $next = floor($input/$to);
    $out = $alphabet[$input-$next*$to].$out; // note alternate % operation
    $input = $next;
  }
  return $out ?: "0";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM