Home > Backend Development > PHP Tutorial > Detailed explanation of usage examples of php bit operators

Detailed explanation of usage examples of php bit operators

伊谢尔伦
Release: 2023-03-10 22:06:02
Original
1682 people have browsed it

Four common bit operations symbols: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise negation) )

& (bitwise AND): When the corresponding bits are 1 at the same time, it is 1 after the & operation, otherwise it is 0

| (bitwise OR): one of the corresponding bits is When 1, it is 1 after the | operation, and when they are both 0, it is 0

^ (bitwise exclusive OR): When the corresponding bits are not 1 at the same time, it is 1 after the ^ operation, and it is 0 at the same time. When it is 0, when it is 1 at the same time, the ^ operation is also 0

~ (bitwise negation): $a+(~$a)=-1

Displacement is mathematics in PHP Operation. Bits moved out in any direction are discarded. When shifting left, the right side is filled with zeros. The sign bit is removed, which means that the positive and negative signs are not retained. The sign bit changes with the change of characters. When shifting right, the left side is filled with the sign bit, and the sign bit remains unchanged.

Note: php does not have unsigned numbers, that is to say, the numbers in php are all signed.

The operations in the computer are all performed in the form of two's complement numbersAddition operations;The php bit operation process is as follows: (Take an 8-bit computer as an example)

With 2&-7=? Calculation as an example:

(1), Calculate 2’s complement:

2->Original code: 00000010->Inverse code: 00000010- >Complement code: 00000010

(2), Calculate the complement code of -7:

-7->Original code: 10000111->Inverse code: 11111000->Complement code : 11111001

(3), Calculate the complement of 2&-7->reverse code->original code

2&-7 complement: 00000000->reverse code: 00000000- >Original code: 00000000

(4), there are 2&-7 original code to get the value of 2&-7

So 2&-7 = 0

The example code is as follows:

<?php
$m=8;
$n=12;
$p=-109;
$mn=$m&$n;
echo $mn."<br>";
$mn=$m|$n;
echo $mn."<br>";
$mn=$m^$n;
echo $mn."<br>";
$mn=~$m;
echo $mn."<br>";
$mn=~$p;
echo $mn."<br>";
?>
Copy after login

Output result:

8
12
4
-9
108
Copy after login

The above is the detailed content of Detailed explanation of usage examples of php bit operators. For more information, please follow other related articles on the PHP Chinese website!

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