search
HomeBackend DevelopmentPHP TutorialDetailed introduction to the usage of php bit operations_PHP tutorial

PHP bit operations are not commonly used in PHP, but they are very useful. Let’s introduce the usage of PHP bit operations.

$a & $b and(bitwise AND)
$a | $b or (bitwise OR)
$a ^ $b Xor (bitwise XOR)
~$a Not(bitwise not)
$a $a >> $b Shift right(shift right)
Detailed explanation
$a & $b bitwise AND sets the bits in $a and $b that are both 1 to 1;
Example: 10 & 12 = 8
10 1010
12 1100
1000 8
$a | $b bitwise OR sets either $a or $b to 1;
Example: 10 | 12 = 14
10 1010
12 1100
1110 14
$a ^ $b bitwise XOR
Example: 10^12
10 1010
12 1100
0110 6
~a Bitwise NOT Set the 0 in $a to 1, and set the 1 to 0
Example: ~10 =
10 1010 111111111111111111111111111111111111111111111111111111111110101 -11
$a Example: 1 1(1) Shift left 10 bits 10000000000(1024)
It is equivalent to 1*2 raised to the 10th power. It is really depressing that there is no power operation in PHP.
$a >> $b right shift Move $a to the right $b times (each move means dividing by 2);
Example: 1024 10000000000(1024) shifted right by 2 bits is 100000000(256)
PHP is the operation $a & $b and (bitwise AND) $a | $b or (bitwise OR) $a ^ $b Xor (bitwise exclusive OR) ~ $a Not (bitwise not) $a > $b Shift right(shift right)
Detailed explanation of $a & $b bitwise AND. Set the bits in $a and $b that are both 1 to 1; example: 10 & 12 = 810 101012 1100 1000 8
$a | $b bitwise OR sets one of $a or $b to 1; example: 10 | 12 = 1410 101012 1100 1110 14
$a ^ $b Bitwise XOR example: 10 ^ 1210 101012 1100 0110 6
~a bitwise notation sets the 0 in $a to 1 and the 1 to 0. Example: ~10 = 10 1010 111111111111111111111111111111111111111111111111111111111110101 -11
$a $a >> $b Right shift moves the value in $a to the right $b times (each move means dividing by 2); example: 1024


The combination of flag bit fields and bit operators


Parameter value list of error_reporting in PHP

value constant
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
2047 E_ALL
2048 E_STRICT
4096 E_RECOVERABLE_ERROR

I found that the values ​​​​of value are all jumping, and they are all 2 to the n+1 power.

Look at this one again. Convert the value of value to binary.

value constant
0000 0001 E_ERROR
0000 0010 E_WARNING
0000 0100 E_PARSE
0000 1000 E_NOTICE
0001 0000 E_CORE_ERROR
0010 0000 E_CORE_WARNING
.
.
.
... ...Every time you add one power, you add one bit to the binary system (almost everyone who has studied computers knows this:)...)
Note: Each option corresponds to a bit (1 means on, 0 means off)

Okay, let’s take a look at the benefits of setting parameters like this.

Let’s take three parameters as an example to see the effect

error_reporting(3);//decbin(3) == 0000 0011; (equivalent to setting E_WARNING and E_ERROR)

error_reporting(4);//decbin(4) == 0000 0100; (equivalent to setting E_PARSE)

error_reporting(5);//decbin(5) == 0000 0101; (equivalent to setting E_PARSE and E_ERROR)

Get settings:

The judgment of whether an item is enabled can be obtained by using bit operations (& - "AND" rule: all 1s are 1, otherwise 0)

//E_PARSE
if($n & 4){
//E_PARSE is on
//The binary number of 4 is 0100, because only the third bit is 1, so when the "&" operation is performed, all other positions are set to 0
//So the result will be greater than 0 only when the third bit of $n is also 1.
//Such as 4(0100),5(0101),6(0110),7(0111)
}else{
//E_PARSE close
//The third bit is 0, which means this option is closed
}

Change settings: ($n represents the current decimal value)

During application, we may set the switch for a certain position as needed.
See usage below.

//Close the E_PARSE item and use the ‘&’ “AND” rule
$n = $n&(8192-4-1);
//Why use 8191?
//This is related to the number of your options. This error display mark uses a total of 13 bits (4096 is 13 bits in binary), while 8192 is (14 bits).
//Why subtract 4 and subtract 1?
//8192-4-1=8187. (1111111111011) The binary number is 13 digits, which is the same as the maximum number of digits we use. And the corresponding value in the third bit is 0.
//Use this number to perform a bitwise "AND" operation with any number between 1 and 4096. Except for the third bit, which will be set to 0, the values ​​of other bits will not change? "AND" rule :)
//Similarly, if you want to turn off E_WARNING
//$n = $n&(8192-2-1);

//Open the E_PARSE item using the ‘|’ “or” rule
$n = $n|4;
//After reading the closing above, you may have some ideas about opening it:)
// ‘|’ — “OR” rule: 1 is 1, otherwise 0
//The above is that when all bits are 1, it does not affect other bits. Now, when all bits are 0, it will not affect other bits:)
//So we only need to set the corresponding value of the binary bit of the subsequent operand to 1, and all other bits to 0 will be OK.
//Did you find it? It happens to be the decimal value corresponding to each of our setting items:)

That’s the idea. If you want to operate the setting values ​​​​on multiple bits at the same time, it depends on how your operands are set.

We can consider this method when developing in the future when we need to set multiple options with one parameter at the same time:)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629039.htmlTechArticlePHP bit operations are not commonly used in PHP, but they are quite useful. Let’s introduce the PHP bits Operation usage. $a $b and (bitwise AND) $a | $b or (bitwise OR) $a ^ $b Xor (bitwise exclusive OR)...
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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools