Return to Snippet

Revision: 18354
at September 29, 2009 01:10 by bucabay


Updated Code
if (!function_exists('bcdiv')) {
	function bcdiv($dividend, $divisor) {
		$quotient = floor($dividend/$divisor);
		return $quotient;
	}
	function bcmod($dividend, $modulo) {
		$remainder = $dividend%$modulo;
		return $remainder;
	}
}

/**
 * Convert Decimal to a base less then 255 comprised of ASCII chars
 *
 * @param Int $num
 * @param Int $base (2-255)
 * @return ASCII String
 */
function base255($num, $base = 255) {
	if ($num < 0) $num = -$num;
	$ret = array();
	while($num > $base) {
		$rem = bcmod($num, $base);
		$num = bcdiv($num, $base);
		$ret[] = chr($rem);
	}
	$ret[] = chr($num);
	return implode('', array_reverse($ret));
}

Revision: 18353
at September 29, 2009 01:03 by bucabay


Initial Code
if (!function_exists('bcdiv')) {
	function bcdiv($dividend, $divisor) {
		$quotient = floor($dividend/$divisor);
		return $quotient;
	}
	function bcmod($dividend, $modulo) {
		$remainder = $dividend/$modulo;
		return $remainder;
	}
}

/**
 * Convert Decimal to a base less then 255 comprised of ASCII chars
 *
 * @param Int $num
 * @param Int $base (2-255)
 * @return ASCII String
 */
function base255($num, $base = 255) {
	if ($num < 0) $num = -$num;
	$ret = array();
	while($num > $base) {
		$rem = bcmod($num, $base);
		$num = bcdiv($num, $base);
		$ret[] = chr($rem);
	}
	$ret[] = chr($num);
	return implode('', array_reverse($ret));
}

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

Initial Description
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.

Initial Title
PHP Base conversion, Radix 255

Initial Tags
php

Initial Language
PHP