[ create a new paste ] login | about

Link: http://codepad.org/Kn9FSx3O    [ raw code | output | fork | 1 comment ]

ninwa - PHP, pasted on Oct 30:
<?php

function dec_to_hex($dec)
{
    $sign = ""; // suppress errors
    if( $dec < 0){ $sign = "-"; $dec = abs($dec); }

    $hex = Array( 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
	              6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 'a',
		          11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e',
		          15 => 'f' );
		
    do
    {
        $h = $hex[($dec%16)] . $h;
		$dec /= 16;
    }
    while( $dec >= 1 );
	
    return $sign . $h;
}

echo dec_to_hex(100) . "\n";
echo dec_to_hex(123) . "\n";
echo dec_to_hex(1)   . "\n";
echo dec_to_hex(-42) . "\n";

?>


Output:
1
2
3
4
64
7b
1
-2a


Create a new paste based on this one


Comments:
posted by ninwa on Oct 30
Converts a decimal number to hex. Supports a much larger range than dechex() including negative values. Uses a simple lookup table.
reply