Home  >  Article  >  Backend Development  >  PHP implements decimal to binary conversion

PHP implements decimal to binary conversion

WBOY
WBOYOriginal
2016-07-25 09:12:201846browse

Example, convert decimal to binary.

  1. //php implements base conversion
  2. function dec2bin ($dec) {
  3. $flag = array();
  4. while ($dec != 0) {
  5. array_push($flag, $dec%2);
  6. $dec = (int)($dec/2);
  7. }
  8. $binstr = '';
  9. while (!emptyempty($flag)) {
  10. $binstr .= array_pop($flag) ;
  11. }
  12. return $binstr;
  13. }
  14. echo dec2bin(7);
Copy code

Note: The above code is used to practice base conversion. PHP has provided built-in functions decbin() and base_convert();

Example:

  1. echo '
    ';

  2. echo base_convert(7,10,2);
  3. echo '
    ';
  4. echo base_convert(1111,2,8);
  5. echo '
    ';

  6. echo decbin(6);

Copy code


Statement:
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