-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdec2hex.php
31 lines (30 loc) · 1013 Bytes
/
dec2hex.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number) {
$hexvalues = array('0','1','2','3','4','5','6','7', '8','9','A','B','C','D','E','F');
$hexval = '';
while($number != '0') {
$hexval = $hexvalues[bcmod($number, '16')].$hexval;
$number = bcdiv($number, '16', 0);
}
return $hexval;
}
// Input: A hexadecimal number as a String.
// Output: The equivalent decimal number as a String.
function hex2dec($number) {
$decvalues = array(
'0' => '0', '1' => '1', '2' => '2',
'3' => '3', '4' => '4', '5' => '5',
'6' => '6', '7' => '7', '8' => '8',
'9' => '9', 'A' => '10', 'B' => '11',
'C' => '12', 'D' => '13', 'E' => '14',
'F' => '15'
);
$decval = '0';
$number = strrev($number);
for ($i = 0; $i < strlen($number); $i++) {
$decval = bcadd(bcmul(bcpow('16', $i, 0), $decvalues[$number{$i}]), $decval);
}
return $decval;
}