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,55 +67,82 @@ 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)
{ {
if ($hex[$i] == '!') $hex = '0' . $hex;
{ $len++;
$j = $i + 1;
$k = $i + 2;
if ($k < $len && ctype_xdigit($hex[$j]) && ctype_xdigit($hex[$k]))
{
// !XY where X and Y are hexadeciman digits
$seg = chr(base_convert(substr($hex, $j, 2), 16, 10));
$i = $k;
}
else if ($j < $len)
{
// !X - X is taken as a character
$seg = $hex[$j];
$i = $j;
}
else
{
// the last charater is a backslash
$seg = $hex[$i];
}
}
else if ($hex[$i] == '|')
{
// colon to slash
$seg = '/';
}
else
{
// normal character
$seg = $hex[$i];
}
$ascii .= $seg;
} }
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 else
{ {
if (strlen($hex) % 2 == 1) $hex = '0' . $hex; $startpos = 1;
}
for($i = 0; $i < strlen($hex); $i += 2)
$ascii .= chr(base_convert(substr($hex, $i, 2), 16, 10)); for ($i = $startpos; $i < $len; $i++)
{
if ($hex[$i] == '!')
{
$j = $i + 1;
$k = $i + 2;
if ($k < $len && ctype_xdigit($hex[$j]) && ctype_xdigit($hex[$k]))
{
// !XY where X and Y are hexadeciman digits
$seg = chr(base_convert(substr($hex, $j, 2), 16, 10));
$i = $k;
}
else if ($j < $len)
{
// !X - X is taken as a character
$seg = $hex[$j];
$i = $j;
}
else
{
// the last charater is a backslash
$seg = $hex[$i];
}
}
else if ($hex[$i] == '|')
{
// colon to slash
$seg = '/';
}
else
{
// normal character
$seg = $hex[$i];
}
$ascii .= $seg;
} }
return $ascii; return $ascii;