轉換函數
/**
* [字符串轉換為(2,8,16進制)ASCII碼]
* @param string $str [待處理字符串]
* @param boolean $encode [字符串轉換為ASCII|ASCII轉換為字符串]
* @param string $intType [2,8,16進制標示]
* @return string byte_str [處理結果]
* @author alexander
*/
function strtoascii($str, $encode=true, $intType="2"){
if($encode == true){
$byte_array = str_split($str);
foreach($byte_array as &$value){
$value = ord($value);
switch ($intType) {
case 16:
$value = sprintf("%02x", $value);
break;
case 8:
$value = sprintf("%03o", $value);
break;
default:
$value = sprintf("%08b", $value);
break;
}
}
unset($value);
$byte_str = implode('', $byte_array);
}
else{
$chunk_size = $intType == 16 ? 2 : ($intType == 8 ? 3 : 8);
$byte_array = chunk_split($str, $chunk_size);
$byte_array = array_filter(explode("\r\n", $byte_array));
foreach($byte_array as &$value){
$fun_name = $intType == 16 ? 'hexdec' : ($intType == 8 ? 'octdec' : 'bindec');
$value = $fun_name($value);
$value = chr($value);
}
unset($value);
$byte_str = implode('', $byte_array);
}
return $byte_str;
}
PHP中的多進制
PHP 整型值可以使用十進制,十六進制,八進制或二進制表示,前面可以加上可選的符號(- 或者 +)。
二進制:[+-]?0b[01]+
八進制:[+-]?0[1-7]+
十進制:[+-]?[1-9][0-9]*|0
十六進制:[+-]?[xX][0-9a-fA-F]+
多進制轉換函數:
bindec 二進制轉換為十進制 decbin 十進制轉換為二進制 octdec 八進制轉換為十進制 decoct 十進制轉換為八進制 hexdec 十六進制轉換為十進制 dechex 十進制轉換為十六進制
以上就是小編為大家帶來的關於PHP中字符串與多進制轉換函數的實例代碼全部內容了,希望大家多多支持~