I have two functions. IsOcta strong> and isHex . It seems that isHex is not working correctly.
The problem with isHex () is that it cannot omit the "x" notation of the original x23 string.
The original hex srting may also be D1CE. Therefore adding x and then comparing will not do.
Is there a proper solution to the isHex function. Also isOcta correct?
function isHex($string){ (int) $x=hexdec("$string"); // Input must be a String and hexdec returns NUMBER $y=dechex($x); // Must be a Number and dechex returns STRING echo "<br />isHex() - Hexa Number Reconverted: ".$y; if($string==$y){ echo "<br /> Result: Hexa "; }else{ echo "<br /> Result: NOT Hexa"; } } function IsOcta($string){ (int) $x=octdec("$string"); // Input must be a String and octdec returns NUMBER $y=decoct($x); // Must be a Number and decoct returns STRING echo "<br />IsOcta() - Octal Number Reconverted: ".$y; if($string==$y){ echo "<br /> Result: OCTAL"; }else{ echo "<br /> Result: NOT OCTAL"; } }
Here is the function call:
$hex = "x23"; // STRING $octa = "023"; // STRING echo "<br / Original HEX = $hex | Original Octa = $octa <br / "; echo isHex($hex)."<br / "; echo IsOcta($octa);
Here is the result of calling the function:
Original HEX = x23 | Original Octa = 023 isHex() - Hexa Number Reconverted: 23 Result: NOT Hexa IsOcta() - Octal Number Reconverted: 23 Result: OCTAL
===== FULL ANSWER ====
Thanks to Layke for invoking a built-in function that checks for HEXA DECIMAL characters in a string or not. Thanks also to Mario for the tip to use ltrim. Both functions were needed to get isHexa or the hex function to be built.
--- EDITED FUNCTION -
// isHEX function function isHex($strings){ // Does not work as originally suggested by Layke, but thanks for directing to the resource. It does not omit 0x representation of a hexadecimal number. /* foreach ($strings as $testcase) { if (ctype_xdigit($testcase)) { echo "<br /> $testcase - <strong>TRUE</strong>, Contains only Hex<br />"; } else { echo "<br /> $testcase - False, Is not Hex"; } } */ // This works CORRECTLY foreach ($strings as $testcase) { if (ctype_xdigit(ltrim($testcase , "0x"))) { echo "<br /> $testcase - <strong>TRUE</strong>, Contains only Hex<br />"; } else { echo "<br /> $testcase - False, Is not Hex"; } } } $strings = array('AB10BC99', 'AR1012', 'x23' ,'0x12345678'); isHex($strings); // calling
Perhaps now, is this stupid proof a โhexadecimalโ function?
suswato
source share