Home  >  Article  >  Backend Development  >  Examples summarizing the usage skills of PHP bit operators

Examples summarizing the usage skills of PHP bit operators

伊谢尔伦
伊谢尔伦Original
2017-06-21 10:08:371746browse

Explain through an example:

<?php
//1.位运算符两边的值必须是整形和浮点型,当是其它类型的值时会先转换成整形和浮点型再来参与位运算;
 //而逻辑运算符两边参与运算的值必须是布尔型;
 var_dump(12&13);//输出 int 12
 //12转换成32位的二进制数为:00000000 00000000 00000000 00001100
 //13转换成32位的二进制数为:00000000 00000000 00000000 00001101
 //按位运算后得到的值为      00000000 00000000 00000000 00001100 ,等于12
 
 var_dump(&#39;A&#39;&&#39;a&#39;);//输出string &#39;A&#39;;因为A=65,a=97
 
 var_dump(&#39;A&#39;&97);//输出int 0;因为字符串A会先转换为整数的0后再参与位运算
 
 //2.位运算与逻辑运算不同没有短路特性
 $a=3;
 $b=10;
 if($a>5&&$b++<100)
 {
     echo "1111111111";
 }
 echo $b."<br>";//输出$b=10,逻辑运算短路,$b没有自加;
 
 if($a>5&$b++<100)
 {
     echo "1111111";
 }
 echo $b."<br>";//输出$b=11,位运算不短路,$b自加;
 
 //3.按位非,按位异或等比较简单,这里不做过多讲叙;现在讲讲按位左移和按位右移动
 var_dump(12>>2);//输出int 3
 var_dump(12<<2);//输出int 48
 //可以发现,左移几位就相当于乘以2的多少次方;按位右移就相当于除以2的多少次方;
 
?>

(1) Determine whether the int type variable a is an odd number or an even number

a&1 = 0 even number

a&1 = 1 odd number

(2) Take the k-th bit of int type variable a (k=0,1,2...sizeof(int)), that is, a>>k&1

(3) Change the int type variable Clear the k-th bit of a to 0, that is, a=a&~(14a64bcb379a0b2f50a5c61985692e427

(4) Set the k-th bit of int type variable a to 1, that is, a=a |(14a64bcb379a0b2f50a5c61985692e427

(5) The int type variable is circularly shifted to the left k times, that is, a=aa8093152e673feb7aba1828c4353209416-k (assume sizeof(int)=16 )

(6) The int type variable a is shifted to the right k times in a loop, that is, a=a>>k|a27507a678509642e376bbb42bbd7a7b6= 0, determine whether it is 2 The power of Without overflow)

a % (2^n) is equivalent to a & (2^n – 1)

(12) The multiplication operation is converted into a bit operation (without In the case of overflow)

a * (2^n) is equivalent to a4e551694d20c19936bd766c59bb29bab> n

Example: 12/8 == 12>>3

(14) a % 2 is equivalent to a & 1

(15) if (x == a) x= b;

  else x= a;

  Equivalent to x= a ^ b ^ x;

(16) The opposite number of In the case of 32 bits, shift left

The above is the detailed content of Examples summarizing the usage skills of PHP bit operators. 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