Home > Backend Development > PHP Tutorial > Example code about string and multi-digit conversion functions in PHP

Example code about string and multi-digit conversion functions in PHP

高洛峰
Release: 2023-03-05 13:02:01
Original
1230 people have browsed it

Conversion function

/**
 * [字符串转换为(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;
}
Copy after login

Multiple bases in PHP

PHP Integer values ​​can be expressed in decimal, hexadecimal, octal or binary, and optional symbols can be added in front (- or +).

Binary: [+-]?0b[01]+

Octal: [+-]?0[1-7]+

Decimal: [+-] ?[1-9][0-9]*|0

Hex: [+-]?[xX][0-9a-fA-F]+

many Base conversion function:

Example code about string and multi-digit conversion functions in PHP

#The above is the entire content of the example code about string and multi-base conversion functions in PHP brought to you by the editor. I hope you will use it. Support PHP Chinese website~

For more related articles about example codes of string and multi-digit conversion functions in PHP, please pay attention to PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template