Decimal to hexadecimal converter

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Decimal to hexadecimal converter

Post 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
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post by tores »

Yepp. Didn't know about it :?
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

:lol:

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