Page 1 of 1

Decimal to hexadecimal converter

Posted: Fri Jan 06, 2006 3:53 am
by tores
Hi

This might be useful...

Code: Select all

/**
 * Converts a number to hexadecimal string 
 *
 * @param number Number to convert
 * @param bool Return hex as dWord or not (I.e. 0x00001234 vs 0x1234)
 * @return string The hex string
 */
function toHex ($number, $dWord = false) {
	/* Inspect arguments */
	if (!is_numeric($number) || !is_bool($dWord)) {
		return '';
	}
	
	/* Set up needed variables */
	$hex = array(0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4',
			5 => '5', 6 => '7', 8 => '8', 9 => '9', 10 => 'A',
			11 => 'B', 12 => 'C', 13 => 'D', 14 => 'E', 15 => 'F');
	$dec = '';
	$last = 0;

	while ($number > 0) {
		for ($i=0; $i < 8; $i++) {
			$h = intval($number / pow(16, $i));
			if ($h < 16) {
				if ($last - $i > 1) {
					/* Add intermediate 0's */
					$dec .= str_repeat('0', $last - $i - 1);
				}
				$dec .= $hex[$h];
				$number -= $h * pow(16, $i);
				if ($number <= 0 && $i > 0) {
					/* Add trailing 0's */
					$dec .= str_repeat('0', $i);
				}
				$last = $i;
				break;
			}
		}
	}
	
	return '0x' . (($dWord) ? sprintf("%08s", $dec) : $dec);
}

Code: Select all

/* Function toHex in use */
echo toHex(15)."\n";
echo toHex(0xF, true)."\n";
echo toHex(0xFF10B)."\n";
echo toHex(0x134E)."\n";
echo toHex(0x5E000, true)."\n";
outputs:

Code: Select all

0xF
0x0000000F
0xFF10B
0x134E
0x0005E000
regards tores

Posted: Fri Jan 06, 2006 4:25 am
by onion2k

Posted: Fri Jan 06, 2006 6:38 am
by tores
Yepp. Didn't know about it :?

Posted: Fri Jan 06, 2006 8:32 am
by Jenk
:lol:

Tis good learning though - for anyone who doesn't know how to convert mathematically but can now see your code :)