search
HomeBackend DevelopmentPHP TutorialHow to achieve hexadecimal conversion in php

How to achieve hexadecimal conversion in php

Jun 04, 2018 am 10:10 AM
phpmethodConvert

In a recent project, base conversion is needed. This problem was something I was very familiar with when I first came into contact with computer theory. However, after not using it for a long time, it actually became blurry...

Converting from decimal to other bases. What is used is to continuously divide the number by the base number to be converted and read the remainder. Just connect them together.

<?php 
/**
 *十进制转二进制、八进制、十六进制 不足位数前面补零*
 *
 * @param array $datalist 传入数据array(100,123,130)
 * @param int $bin 转换的进制可以是:2,8,16
 * @return array 返回数据 array() 返回没有数据转换的格式
 */
function decto_bin($datalist,$bin)
{
  static $arr=array(0,1,2,3,4,5,6,7,8,9,&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;);
  if(!is_array($datalist)) $datalist=array($datalist);
  if($bin==10)return $datalist; //相同进制忽略
  $bytelen=ceil(16/$bin); //获得如果是$bin进制,一个字节的长度
  $aOutChar=array();
  foreach ($datalist as $num)
  {
    $t="";
    $num=intval($num);
  if($num===0)continue;
    while($num>0)
    {
      $t=$arr[$num%$bin].$t;
      $num=floor($num/$bin);
    }
    $tlen=strlen($t);
    if($tlen%$bytelen!=0)
    {
    $pad_len=$bytelen-$tlen%$bytelen;
    $t=str_pad("",$pad_len,"0",STR_PAD_LEFT).$t; //不足一个字节长度,自动前面补充0
    }
    $aOutChar[]=$t;
  }
  return $aOutChar;
}

Test:

var_dump(decto_bin(array(128,253),2));
var_dump(decto_bin(array(128,253),8));
var_dump(decto_bin(array(128,253),16));

X-Powered-By: PHP/5.2.0
Content-type: text/html

array(2) {
 [0]=>
 string(8) "10000000"
 [1]=>
 string(8) "11111101"
}
array(2) {
 [0]=>
 string(4) "0200"
 [1]=>
 string(4) "0375"
}
array(2) {
 [0]=>
 string(2) "80"
 [1]=>
 string(2) "FD"
}

Binary, octal, hexadecimal System to decimal

This conversion uses multiplication, such as: 1101 to decimal: 1*2^3 1*2^2 0*2^1 1*2^0

Code:

<?php 
/**
 *二进制、八进制、十六进制 转十进制*
 *
 * @param array $datalist 传入数据array(df,ef)
 * @param int $bin 转换的进制可以是:2,8,16
 * @return array 返回数据 array() 返回没有数据转换的格式
 * @copyright chengmo QQ:8292669
 */
function bin_todec($datalist,$bin)
{
  static $arr=array(&#39;0&#39;=>0,&#39;1&#39;=>1,&#39;2&#39;=>2,&#39;3&#39;=>3,&#39;4&#39;=>4,&#39;5&#39;=>5,&#39;6&#39;=>6,&#39;7&#39;=>7,&#39;8&#39;=>8,&#39;9&#39;=>9,&#39;A&#39;=>10,&#39;B&#39;=>11,&#39;C&#39;=>12,&#39;D&#39;=>13,&#39;E&#39;=>14,&#39;F&#39;=>15);
  if(!is_array($datalist))$datalist=array($datalist);
  if($bin==10)return $datalist; //为10进制不转换
  $aOutData=array(); //定义输出保存数组
  foreach ($datalist as $num)
  {
    $atnum=str_split($num); //将字符串分割为单个字符数组
    $atlen=count($atnum);
    $total=0;
    $i=1;
    foreach ($atnum as $tv)
    {
      $tv=strtoupper($tv);
       
      if(array_key_exists($tv,$arr))
      {
        if($arr[$tv]==0)continue;
        $total=$total+$arr[$tv]*pow($bin,$atlen-$i);
      }
      $i++;
    }
    $aOutData[]=$total;
  }
  return $aOutData;
}

Test:

var_dump(bin_todec(array(&#39;ff&#39;,&#39;ff33&#39;,&#39;cc33&#39;),16));
var_dump(bin_todec(array(&#39;1101101&#39;,&#39;111101101&#39;),2));
var_dump(bin_todec(array(&#39;1234123&#39;,&#39;12341&#39;),8));

X-Powered-By: PHP/5.2.0
Content-type: text/html

array(3) {
 [0]=>
 int(255)
 [1]=>
 int(65331)
 [2]=>
 int(52275)
}
array(2) {
 [0]=>
 int(124)
 [1]=>
 int(508)
}
array(2) {
 [0]=>
 int(342099)
 [1]=>
 int(5345)
}

These are just implementation methods, in fact Regardless of the PHP language or other languages, the implementation ideas are the same. PHP actually has many built-in functions to complete these contents:

bindec(), decoct(), dechex() base_convert() decbin() This is just an implementation idea. hehe!

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php Detailed explanation of the definition and usage examples of parse_str() function

Two methods for determining string length in PHP

phpUsing ffmpeg to add text subtitles to videos

The above is the detailed content of How to achieve hexadecimal conversion in php. For more information, please follow other related articles on the PHP Chinese website!

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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor