-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecToHex.php
More file actions
34 lines (34 loc) · 1.1 KB
/
DecToHex.php
File metadata and controls
34 lines (34 loc) · 1.1 KB
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
32
33
34
<?php
const MAX_INT = 2 ** 32 - 1;
echo("Input an unsigned integer number\r\n");
$uNum = intval(chop(fgets(STDIN)));
if(($uNum < 0) or ($uNum > MAX_INT))
{
echo("Invalid number format");
exit(0);
}
echo("Lower case ? (y/n) ");
$chAnswer = fgetc(STDIN);
$bLowerCase = (($chAnswer == "y") or ($chAnswer == "Y"));
$uTempVal = $uNum;
$strHexNum = "";
while ($uTempVal > 0)
{
$chHexDigit = '\0';
$nHexDigit = $uTempVal % 16;
if($nHexDigit >= 0 && $nHexDigit <= 9)
$chHexDigit = chr($nHexDigit + ord("0"));
else if($nHexDigit >= 10 && $nHexDigit <= 15 && $bLowerCase)
$chHexDigit = chr($nHexDigit - 10 + ord("a"));
else if($nHexDigit >= 10 && $nHexDigit <= 15)
$chHexDigit = chr($nHexDigit - 10 + ord("A"));
$strHexNum = $chHexDigit . $strHexNum;
$uTempVal = intdiv($uTempVal, 16);
}
if(strlen($strHexNum) == 0)
{
$strHexNum = "0";
}
printf("The hexadecimal equivalent of the decimal number %d is %s\r\n", $uNum, $strHexNum);
fgetc(STDIN);
?>