Home  >  Article  >  How to understand the left shift and right shift operators in C language

How to understand the left shift and right shift operators in C language

清浅
清浅Original
2019-03-11 17:28:2256348browse

Left shift in C language means left shift operator, which means discarding the highest bit and then adding 0 to the lowest bit; while right shift in C language means right shift operator, which is the opposite of left shift. It moves a few places to the right.

How to understand the left shift and right shift operators in C language

Usage of left shift and right shift operators in C language: left shift operator discards the highest bit and then fills the lowest bit with 0; right shift The algorithm is the opposite of left shift. It moves a few bits to the right.

The left shift and right shift operators in C language are operators in C language. Next, we will introduce them to you in detail in the article. How to use these two operators has certain reference value. I hope it will be helpful to everyone

[Recommended courses:C Language Tutorial

Let’s talk about left shift first. Left shift is to move all the bits of a number to the left by a certain number of bits. Use the 887c6109733a9389a8bdf2525a4f948f The sign bit will be kept unchanged, for example:

int i = 0x80000000;
i = i >> 1;  //i的值不会变成0x40000000,而会变成0xc0000000

That is to say, after the sign bit is moved to the right, 0 will be added for positive numbers and 1 for negative numbers, which is the arithmetic right shift in assembly language. Similarly When the number of bits moved exceeds the length of the type, the remainder is taken, and then the remainder is moved.

负数10100110 >>5(假设字长为8位),则得到的是  11111101

In short, in C, left shift is logical/arithmetic left shift (the two are exactly the same ), right shift is an arithmetic right shift, which will keep the sign bit unchanged. In actual applications, you can use left/right shift to perform fast multiplication/division operations according to the situation, which will be much more efficient than looping.

The above is the detailed content of How to understand the left shift and right shift operators in C language. 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