2

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?

1 Answer 1

1

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";
}
Sign up to request clarification or add additional context in comments.

2 Comments

base_convert($input,10,32) does the 'trick' very well. Many thanks!
eh, just one question: How do i convert it back to an unsigned int?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.