HexDecBinCalc/conversions.php

97 lines
2.8 KiB
PHP

<?php
function hex_to_decimal(string $hex) : int {
$hex = sanitize_string_input($hex);
$chars = 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);
$decimal = 0;
$hex_chars = str_split(strrev(strtoupper($hex)));
for ($i = 0; $i < sizeof($hex_chars); $i++) {
$decimal += $chars[$hex_chars[$i]] * (16 ** $i);
}
return $decimal;
}
function hex_to_binary(string $hex) : int {
$hex = sanitize_string_input($hex);
$decimal = hex_to_decimal($hex);
return decimal_to_binary($decimal);
}
function decimal_to_hex(int $decimal) : string {
$decimal = sanitize_int_input($decimal);
$chars = 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");
$remainder = $decimal;
$hex_string = "";
while ($remainder > 0) {
if ($remainder < 16) {
$hex_string = $chars[$remainder] . $hex_string;
break;
} else {
$temp_remainder = $remainder % 16;
$quotient = ($remainder - $temp_remainder) / 16;
$hex_string = $chars[$temp_remainder] . $hex_string;
$remainder = $quotient;
}
}
return $hex_string;
}
function decimal_to_binary(int $decimal) : int {
$decimal = sanitize_int_input($decimal);
$remainder = $decimal;
$greatest_base_2 = 0;
$binary_str = "";
for ($i = 0; (2 ** $i) < $remainder; $i++) {
$greatest_base_2 = $i;
}
while ($greatest_base_2 >= 0) {
if ($remainder < (2 ** $greatest_base_2)) {
$binary_str = $binary_str . "0";
} else {
$remainder = $remainder - (2 ** $greatest_base_2);
$binary_str = $binary_str . "1";
}
$greatest_base_2--;
}
return intval($binary_str);
}
function binary_to_decimal(int $binary) : int {
$binary = sanitize_int_input($binary);
$digits = str_split(strrev(strval($binary)));
$decimal = 0;
for ($i = 0; $i < sizeof($digits); $i++) {
if ($digits[$i] == "1") {
$decimal = $decimal + (2 ** $i);
}
}
return $decimal;
}
function binary_to_hex(int $binary) : string {
$binary = sanitize_int_input($binary);
$decimal = binary_to_decimal($binary);
return decimal_to_hex($decimal);
}
function sanitize_int_input(int $input) : int {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return intval($input);
}
function sanitize_string_input(string $input) : string {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return strval($input);
}