PHP Base conversion, Radix 255


/ Published in: PHP
Save to your folder(s)

Allows you to convert to any base between 2 and 255, effectively using all the ASCII characters.

In order to convert very large numbers with arbitrary precision you’ll need the BCMath lib. Without BCMath the large numbers will not be converted correctly due to PHP not being able to do the arithmetic.


Copy this code and paste it in your HTML
  1. if (!function_exists('bcdiv')) {
  2. function bcdiv($dividend, $divisor) {
  3. $quotient = floor($dividend/$divisor);
  4. return $quotient;
  5. }
  6. function bcmod($dividend, $modulo) {
  7. $remainder = $dividend%$modulo;
  8. return $remainder;
  9. }
  10. }
  11.  
  12. /**
  13.  * Convert Decimal to a base less then 255 comprised of ASCII chars
  14.  *
  15.  * @param Int $num
  16.  * @param Int $base (2-255)
  17.  * @return ASCII String
  18.  */
  19. function base255($num, $base = 255) {
  20. if ($num < 0) $num = -$num;
  21. $ret = array();
  22. while($num > $base) {
  23. $rem = bcmod($num, $base);
  24. $num = bcdiv($num, $base);
  25. $ret[] = chr($rem);
  26. }
  27. $ret[] = chr($num);
  28. return implode('', array_reverse($ret));
  29. }

URL: http://www.bucabay.com/php/base-conversion-in-php-radix-255/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.