enhanced HexToAscii() to handle anomaly in a hexadecimal string

This commit is contained in:
hyung-hwan 2017-10-13 07:11:08 +00:00
parent d2ad4e53dc
commit c6808d6530

View File

@ -67,11 +67,46 @@ class Converter
function HexToAscii($hex) function HexToAscii($hex)
{ {
$ascii = ''; $ascii = '';
$is_hex = FALSE;
$len = strlen($hex); $len = strlen($hex);
if ($len > 0 && $hex[0] == '!') if ($len <= 0) return $ascii;
if ($hex[0] != '!')
{ {
for ($i = 1; $i < $len; $i++) $orglen = $len;
$is_hex = 1;
if ($len % 2 == 1)
{
$hex = '0' . $hex;
$len++;
}
for($i = 0; $i < $len; $i += 2)
{
if (!ctype_xdigit($hex[$i]) || !ctype_xdigit($hex[$i + 1]))
{
$ascii = '';
$is_hex = FALSE;
break;
}
$ascii .= chr(base_convert(substr($hex, $i, 2), 16, 10));
}
if ($is_hex > 0) return $ascii;
# if the string not prefixed with '!' contains non-hexadecimal character,
# arrange it to treat it as if it's prefixed with '!'.
$startpos = $len - $orglen;
}
else
{
$startpos = 1;
}
for ($i = $startpos; $i < $len; $i++)
{ {
if ($hex[$i] == '!') if ($hex[$i] == '!')
{ {
@ -109,14 +144,6 @@ class Converter
$ascii .= $seg; $ascii .= $seg;
} }
}
else
{
if (strlen($hex) % 2 == 1) $hex = '0' . $hex;
for($i = 0; $i < strlen($hex); $i += 2)
$ascii .= chr(base_convert(substr($hex, $i, 2), 16, 10));
}
return $ascii; return $ascii;
} }