search
HomeBackend DevelopmentPHP TutorialPHP implements hexadecimal conversion (binary, octal, hexadecimal) and mutual conversion code

Convert decimal to binary, octal, hexadecimal
To convert from decimal to other bases, just use the number to divide it 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() 返回没有数据转换的格式 
* @copyright chengmo QQ:8292669 
*/ 
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 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('ff','ff33','cc33'),16));
var_dump(bin_todec(array('1101101','111101101'),2));
var_dump (bin_todec(array('1234123','12341'),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)
}
Later words, these It's just the implementation method. In fact, it doesn't matter whether it's PHP language or something else, 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.

For more PHP implementation of base conversion (binary, octal, hexadecimal) and mutual conversion code related articles, please pay attention to 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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),