Home php教程 php手册 php移位运算、移位操作学习笔记

php移位运算、移位操作学习笔记

May 25, 2016 pm 04:49 PM
php Operation

位运算应用口诀

清零取位要用与,某位置一可用或

若要取反和交换,轻轻松松用异或

移位运算

要点

1 它们都是双目运算符,两个运算分量都是整形,结果也是整形。

2 "

3 ">>"右移:右边的位被挤掉。对于左边移出的空位,如果是正数则空位补0,若为负数,可能补0或补1,这取决于所用的计算机系统。

4 ">>>"运算符,右边的位被挤掉,对于左边移出的空位一概补上0。

位运算符的应用 (源操作数s 掩码mask)

(1) 按位与-- &

1 清零特定位 (mask中特定位置0,其它位为1,s=s&mask)

2 取某数中指定位 (mask中特定位置1,其它位为0,s=s&mask)

(2) 按位或-- |

常用来将源操作数某些位置1,其它位不变。 (mask中特定位置1,其它位为0 s=s|mask)

(3) 位异或-- ^

1 使特定位的值取反 (mask中特定位置1,其它位为0 s=s^mask)

2 不引入第三变量,交换两个变量的值 (设 a=a1,b=b1)

目 标           操 作              操作后状态

a=a1^b1         a=a^b              a=a1^b1,b=b1

b=a1^b1^b1      b=a^b              a=a1^b1,b=a1

a=b1^a1^a1      a=a^b              a=b1,b=a1

二进制补码运算公式:

-x = ~x + 1 = ~(x-1)

~x = -x-1

-(~x) = x+1

~(-x) = x-1

x+y = x - ~y - 1 = (x|y)+(x&y)

x-y = x + ~y + 1 = (x|~y)-(~x&y)

x^y = (x|y)-(x&y)

x|y = (x&~y)+y

x&y = (~x|y)-~x

x==y:    ~(x-y|y-x)

x!=y:    x-y|y-x

x

x

x

x

应用举例

(1) 判断int型变量a是奇数还是偶数          

a&1   = 0 偶数

a&1 =   1 奇数

(2) 取int型变量a的第k位 (k=0,1,2……sizeof(int)),即a>>k&1

(3) 将int型变量a的第k位清0,即a=a&~(1

(4) 将int型变量a的第k位置1, 即a=a|(1

(5) int型变量循环左移k次,即a=a>16-k   (设sizeof(int)=16)

(6) int型变量a循环右移k次,即a=a>>k|a

(7)整数的平均值

对于两个整数x,y,如果用 (x+y)/2 求平均值,会产生溢出,因为 x+y 可能会大于INT_MAX,但是我们知道它们的平均值是肯定不会溢出的,我们用如下算法:

int average(int x, int y)   //返回X,Y 的平均值 
{   
     return (x&y)+((x^y)>>1); 
}
Copy after login

(8)判断一个整数是不是2的幂,对于一个数 x >= 0,判断他是不是2的幂

boolean power2(int x) 
{ 
    return ((x&(x-1))==0)&&(x!=0); 
}
Copy after login

(9)不用temp交换两个整数

void swap(int x , int y) 
{ 
    x ^= y; 
    y ^= x; 
    x ^= y; 
}
Copy after login

(10)计算绝对值

int abs( int x ) 
{ 
int y ; 
y = x >> 31 ; 
return (x^y)-y ;        //or: (x+y)^y 
}
Copy after login

(11)取模运算转化成位运算 (在不产生溢出的情况下)

a % (2^n) 等价于 a & (2^n - 1)

(12)乘法运算转化成位运算 (在不产生溢出的情况下)

a * (2^n) 等价于 a<< n

(13)除法运算转化成位运算 (在不产生溢出的情况下)

a / (2^n) 等价于 a>> n 例: 12/8 == 12>>3

(14) a % 2 等价于 a & 1

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

else x= a;等价于 x= a ^ b ^ x;

(16) x 的 相反数 表示为 (~x+1)

最后补充一些关于二进制位移操作

PHP主要是设计于文本操作的,其实PHP不适合做数学运算,效率也不高,不过因为这次的项目中有个东西必须使用到二进制位移操作,在PHP上面遇到了一些麻烦。

因为PHP只有32位有符号整数,没有64位长整型,也没有无符号整数。其整型的范围是-231-1~231,超出这个范围的,将被解释为浮点数。因此,0xFFFFFFFF,直接打印,显示的是4294967295,及232:

>> 0xFFFFFFFFF

4294967295

>> gettype(0xFFFFFFFF)

'double'

而在32位有符号整型中,0xFFFFFFFF应表示-1:

>> (int)0xFFFFFFFFF

-1

而PHP不支持浮点数的二进制位移操作,如果要进行,会先转换为整型,最后的结果,也将按照整型来返回:

>> 1 << 31 
-2147483648 
>> 1 << 30 
1073741824 
>> 1 << 32 
1 
>> 0xFFFFFFFF >> 1 
-1
Copy after login

同时PHP的向右位移操作,高位会填充符号位,而且PHP没有提供类似Java的>>>来强制填充0:

>> 1 << 32 
1 
>> 0xFFFFFFFF >> 1 
-1 
>> 0xFFFFFFFF >> 2 
-1 
>> 0xFFFFFFFF >> 3 
-1 
>> 0xFFFFFFFF >> 31 
-1
Copy after login

如何解决这个问题呢,我考虑过使用BCMath数学函数库,直接处理字符串表示的整数,或者是GMP/BigInt扩展等。不过我想既然使用字符串,那么我可以字符串地彻底一些,把数字转换成32个二进制的字符串,再手工填充0,最后转换回来。

不知道哪位有更好的方法,请告诉我,另外,其实代码可以扩展为任意位2进制的位移操作,这里我没有做,PHP代码如下:

<?php
/** 
 * 无符号32位右移
 * @param mixed $x 要进行操作的数字,如果是字符串,必须是十进制形式
 * @param string $bits 右移位数
 * @return mixed 结果,如果超出整型范围将返回浮点数
 */
function shr32($x, $bits) {
    // 位移量超出范围的两种情况
    if ($bits <= 0) {
        return $x;
    }
    if ($bits >= 32) {
        return 0;
    }
    //转换成代表二进制数字的字符串
    $bin = decbin($x);
    $l = strlen($bin);
    //字符串长度超出则截取底32位,长度不够,则填充高位为0到32位
    if ($l > 32) {
        $bin = substr($bin, $l - 32, 32);
    } elseif ($l < 32) {
        $bin = str_pad($bin, 32, &#39;0&#39;, STR_PAD_LEFT);
    }
    //取出要移动的位数,并在左边填充0
    return bindec(str_pad(substr($bin, 0, 32 - $bits) , 32, &#39;0&#39;, STR_PAD_LEFT));
}
/** 
 * 无符号32位左移
 * @param mixed $x 要进行操作的数字,如果是字符串,必须是十进制形式
 * @param string $bits 左移位数
 * @return mixed 结果,如果超出整型范围将返回浮点数
 */
function shl32($x, $bits) {
    // 位移量超出范围的两种情况
    if ($bits <= 0) {
        return $x;
    }
    if ($bits >= 32) {
        return 0;
    }
    //转换成代表二进制数字的字符串
    $bin = decbin($x);
    $l = strlen($bin);
    //字符串长度超出则截取底32位,长度不够,则填充高位为0到32位
    if ($l > 32) {
        $bin = substr($bin, $l - 32, 32);
    } elseif ($l < 32) {
        $bin = str_pad($bin, 32, &#39;0&#39;, STR_PAD_LEFT);
    }
    //取出要移动的位数,并在右边填充0
    return bindec(str_pad(substr($bin, $bits) , 32, &#39;0&#39;, STR_PAD_RIGHT));
}
?>
Copy after login

文章链接:

随便收藏,请保留本文地址!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles