How to understand the left shift and right shift operators in C language
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.
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 << operator in C. For example:
int i = 1; i = i << 2; //把i里的值左移2位
That is to say, the binary system of 1 is 000...0001 (the number of 0s in front of 1 here is related to the number of digits in int. On a 32-bit machine, there are 31 in gcc 0), after shifting 2 bits to the left, it becomes 000...0100, which is 4 in decimal. Therefore, shifting 1 bit to the left is equivalent to multiplying by 2, then shifting n bits to the left is multiplying by 2 raised to the nth power. (Signed numbers are not fully applicable, because the left shift may cause the sign to change. The reason is explained below)
One problem that needs attention is that the sign bit of the m end is not reported on the leftmost bus of the int type and the shift is moved out Situation. We know that int is a signed integer, and the leftmost 1 bit is the sign bit, that is, 0 positive and 1 negative. Then overflow will occur when shifting, for example:
int i = 0x40000000; //16进制的40000000,为2进制的01000000...0000 i = i << 1;
Then, after i is shifted to the left by 1 bit, it will become 0x80000000, which is 100000...0000 in binary. The sign bit is set to 1, and the other bits are all 0, which becomes the minimum value that the int type can represent. , the value of 32-bit int is -2147483648, overflowing. What will happen if i is then shifted to the left by 1 bit? In C language, the highest bit is discarded. After discarding 1, the value of i becomes becomes 0.
A special case in left shift is that when the number of digits shifted to the left exceeds the maximum number of digits of the numerical type, the compiler will use the number of digits shifted left to modulo the maximum number of digits of the type, and then Shift according to the remainder, such as:
int i = 1, j = 0x80000000; //设int为32位 i = i << 33; // 33 % 32 = 1 左移1位,i变成2 j = j << 33; // 33 % 32 = 1 左移1位,j变成0,最高位被丢弃
When compiling this program with gcc, the compiler will give a warning, saying that the number of left shifts >= type length. Then In fact, i and j are moved by 1 bit, which is the remainder after 332. This is the rule under
gcc. It is not clear whether it is the same for other compilers.
In short, the left shift is: discard the highest bit and fill the lowest bit with 0
Let’s talk about right shift. If you understand the principle of left shift, then right shift will be easier to understand.
The concept of right shift and The opposite of left shift is to move a few bits to the right. The operator is > 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

Algorithms are the set of instructions to solve problems, and their execution speed and memory usage vary. In programming, many algorithms are based on data search and sorting. This article will introduce several data retrieval and sorting algorithms. Linear search assumes that there is an array [20,500,10,5,100,1,50] and needs to find the number 50. The linear search algorithm checks each element in the array one by one until the target value is found or the complete array is traversed. The algorithm flowchart is as follows: The pseudo-code for linear search is as follows: Check each element: If the target value is found: Return true Return false C language implementation: #include#includeintmain(void){i

Troubleshooting Tips for C language processing files When processing files in C language, you may encounter various problems. The following are common problems and corresponding solutions: Problem 1: Cannot open the file code: FILE*fp=fopen("myfile.txt","r");if(fp==NULL){//File opening failed} Reason: File path error File does not exist without file read permission Solution: Check the file path to ensure that the file has check file permission problem 2: File reading failed code: charbuffer[100];size_tread_bytes=fread(buffer,1,siz

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.