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