刷题记录-ASCII码 (转字符串)
ASCII码
https://www.nowcoder.com/practice/4280d330fe314e8f98cd5c593e3e9190
题目:转换以下ASCII码为对应字符并输出他们。
73, 32, 99, 97, 110, 32, 100, 111, 32, 105, 116 , 33
注意,当数值少于128,原样输出。
以下代码参考了网上一个PHP实现ASCII码与字符串转换的写法。(https://www.jb51.net/article/112523.htm )
<?php class ascii{ function decode($str,$prefix="&#"){ $str = str_replace($prefix,"",$str); $a = explode(";",$str); foreach($a as $dec){ if ($dec < 128){ $utf .= chr($dec); } elseif ($dec < 2048){ $utf .= chr(192 + (($dec - ($dec%64)) / 64)); $utf .= chr(128 + ($dec % 64)); } else { $utf .= chr(224 + (($dec - ($dec % 4096)) / 4096)); $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64)); $utf .= chr(128 + ($dec % 64)); } } return $utf; } } $exc = new ascii; print($exc->decode('73')); print($exc->decode('32')); print($exc->decode('99')); print($exc->decode('97')); print($exc->decode('110')); print($exc->decode('32')); print($exc->decode('100')); print($exc->decode('111')); print($exc->decode('32')); print($exc->decode('105')); print($exc->decode('116')); print($exc->decode('33'));