2009年10月22日 星期四

PHP 字元轉換二、八、十、十六進位

二進位二進制(B,Binary)00000010=2
八進位八進制(O,Octal)00000010=8
十進位十進制(D,Decimalist)00000010=10
十進位十六進制(H,Hex)00000010=16

Binary 跟 ASCII互轉

 
function asc2bin($str) {
$text_array = explode("\r\n", chunk_split($str, 1));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= substr("0000".base_convert(ord($text_array[$n]), 10, 2), -8);
}
$newstring = chunk_split($newstring, 8, " ");
return $newstring;
}

function bin2asc($str) {
$str = str_replace(" ", "", $str);
$text_array = explode("\r\n", chunk_split($str, 8));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= chr(base_convert($text_array[$n], 2, 10));
}
return $newstring;
}

ASCII 與 HEX互轉
 
function asc2hex($str) {
return chunk_split(bin2hex($str), 2, " ");
}

function hex2asc($str) {
$str = str_replace(" ", "", $str);
for ($n=0; $n<strlen($str); $n+=2) {
$newstring .= pack(&quot;C&quot;, hexdec(substr($str, $n, 2)));
}

return $newstring;
}

Binary 與 HEX互轉
 
function binary2hex($str) {
$str = str_replace(" ", "", $str);
$text_array = explode("\r\n", chunk_split($str, 8));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= base_convert($text_array[$n], 2, 16);
}
$newstring = chunk_split($newstring, 2, " ");
return $newstring;
}

function hex2binary($str) {
$str = str_replace(" ", "", $str);
$text_array = explode("\r\n", chunk_split($str, 2));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= substr("0000".base_convert($text_array[$n], 16, 2), -8);
}
$newstring = chunk_split($newstring, 8, " ");
return $newstring;
}
引用:Nightmare的胡言亂語-利用PHP來做字元碼轉換(Binary、ASCII、HEX互轉)

沒有留言:

張貼留言