search
HomeBackend DevelopmentPHP TutorialPHP shift operation, shift operation study notes_PHP tutorial

The following are some commonly used study notes on PHP shift operations and shift operations. I hope the article will bring value to all students.

Bit operation application tips

To clear the bit, use AND, a certain position is available or

To negate and swap, easily use XOR

Shift operation

Point 1 They are both binary operators, both operation components are integers, and the result is also an integer.

2 "

3 ">>"Shift right: The bit on the right is squeezed out. For the empty bits moved out from the left, if it is a positive number, the empty bit is filled with 0. If it is a negative number, it may be filled with 0 or 1, depending on the computer system used.

4 ">>>" operator, the bits on the right are squeezed out, and the vacancies shifted out on the left are filled with 0.

Application of bitwise operators (source operand s mask mask)

(1) Bitwise AND-- &

1 Clear specific bits (specific bits in mask are 0, other bits are 1, s=s&mask)

2 Take the specified bit in a certain number (the specific position in the mask is 1, other bits are 0, s=s&mask)

(2) Bitwise OR-- |

Often used to set certain bits of the source operand to 1, leaving other bits unchanged. (Specific position in mask is 1, other bits are 0 s=s|mask)

(3) Bit XOR-- ^

1 inverts the value of a specific bit (the specific position in the mask is 1, other bits are 0 s=s^mask)

2 Do not introduce the third variable, exchange the values ​​​​of the two variables (assume a=a1,b=b1)

Target Operation Status after operation

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

Two’s complement arithmetic formula:

-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

Application examples

(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) Clear the k-th bit of int type variable a to 0, that is, a=a&~(1

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

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

(6) The int type variable a is cyclically shifted to the right k times, that is, a=a>>k|a

(7) Average of integers

For two integers x, y, if you use (x+y)/2 to calculate the average, overflow will occur, because x+y may be greater than INT_MAX, but we know that their average will definitely not overflow. , we use the following algorithm:

int average(int x, int y) //Return the average of X, Y

{

return (x&y)+((x^y)>>1);

}

(8) Determine whether an integer is a power of 2. For a number x >= 0, determine whether it is a power of 2

boolean power2(int x)

{

return ((x&(x-1))==0)&&(x!=0);

}

(9) Exchange two integers without temp

void swap(int x , int y)

{

x ^= y;

y ^= x;

x ^= y;

}

(10) Calculate absolute value

int abs( int x )

{

int y ;

y = x >> 31 ;

return (x^y)-y ;   //or: (x+y)^y

}

(11) Modulo operation is converted into bit operation (without overflow)

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

(12) Multiplication operations are converted into bit operations (without overflow)

a * (2^n) is equivalent to a

(13) The division operation is converted into a bit operation (without overflow)

a / (2^n) is equivalent to a>> 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 of x is expressed as (~x+1)

Finally add some information about binary shift operation


PHP is mainly designed for text operations. In fact, PHP is not suitable for mathematical operations and its efficiency is not high. However, because there is something in this project that must use binary displacement operations, I encountered some troubles in PHP.

Because PHP only has 32-bit signed integers, no 64-bit long integers, and no unsigned integers. The range of its integer type is -231-1~231. Anything outside this range will be interpreted as a floating point number. Therefore, 0xFFFFFFFF, printed directly, displays 4294967295, and 232:


>> 0xFFFFFFFF
4294967295
>> gettype(0xFFFFFFFF)
'double'


In a 32-bit signed integer, 0xFFFFFFFF should represent -1:


>> (int)0xFFFFFFFFF
-1


PHP does not support the binary shift operation of floating point numbers. If it is to be performed, it will be converted to an integer first, and the final result will also be returned as an integer:


>> 1 -2147483648
>> 1 1073741824
>> 1 1
>> 0xFFFFFFFF >> 1
-1


At the same time, PHP's right shift operation will fill the sign bit in the high bits, and PHP does not provide a Java-like >>> to force filling of 0:

>> 1 1
>> 0xFFFFFFFF >> 1
-1
>> 0xFFFFFFFF >> 2
-1
>> 0xFFFFFFFF >> 3
-1
>> 0xFFFFFFFF >> 31
-1


How to solve this problem? I have considered using the BCMath math function library to directly process integers represented by strings, or GMP/BigInt extensions. But I think since I am using strings, I can be more thorough with strings, convert the numbers into 32 binary strings, then manually fill in 0s, and finally convert them back.

I don’t know if anyone has a better method, please tell me.

The code is as follows:
Download the code directly: shift.php
(In addition, the code can actually be expanded to any binary bit shift operation, but I did not do it here)

PHP

 代码如下 复制代码
/**
 * 无符号32位右移
 * @param mixed $x 要进行操作的数字,如果是字符串,必须是十进制形式
 * @param string $bits 右移位数
 * @return mixed 结果,如果超出整型范围将返回浮点数
 */
function shr32($x, $bits){
    // 位移量超出范围的两种情况
    if($bits         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         $bin = str_pad($bin, 32, '0', STR_PAD_LEFT);
    }
    //取出要移动的位数,并在左边填充0
    return bindec(str_pad(substr($bin, 0, 32 - $bits), 32, '0', STR_PAD_LEFT));
}
/**
 * 无符号32位左移
 * @param mixed $x 要进行操作的数字,如果是字符串,必须是十进制形式
 * @param string $bits 左移位数
 * @return mixed 结果,如果超出整型范围将返回浮点数
 */ 
function shl32 ($x, $bits){
    // 位移量超出范围的两种情况
    if($bits         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         $bin = str_pad($bin, 32, '0', STR_PAD_LEFT);
    }
    //取出要移动的位数,并在右边填充0
    return bindec(str_pad(substr($bin, $bits), 32, '0', STR_PAD_RIGHT));
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632618.htmlTechArticleThe following are some commonly used study notes about PHP shift operations and shift operations. I hope the article will be useful to all students. value. Tips for applying bit operations. To clear a bit, use AND. A certain position is available 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
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

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 Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.