如题,正在学习C语言,其中有个知识点是按位运算,跟着书上的介绍和动手去写示例程序明白白其中的原理了。就是对存储在内存中的一个或两个值的位进行运算,也会对两个值进行按位与、按位或、取反等的操作。
自己一点粗略的理解是通过对内存的直接操作可以节省资源提高效率。
请问这个知识点的应用点是在哪里?比如:最常用在什么场景中,大概哪类程序中?再能举几个例子最好拉。
补充:感谢大家的热心回答,基本能解除我的疑惑了。
PHPz2017-04-17 13:08:13
For example, in a thirty-two-bit number, each bit represents an interrupt. To clear a certain bit, use AND. If you want to set a certain bit, use OR.
PHP中文网2017-04-17 13:08:13
You can use shift operations to optimize efficiency, and you can use 1 bit space for flags
迷茫2017-04-17 13:08:13
For example, there is an 8-bit binary integer. 1 in each bit represents power on and 0 represents power off. If we want to turn 8 switches on and off one by one, we need to use bit operations. You can look at the code of the microcontroller
PHP中文网2017-04-17 13:08:13
If you use displacement to calculate, it is best to leave it to the compiler for optimization, such as x<<12, for example, directly x*1024. One of the commonly used
bits is the flag bit. For example, what are the characteristics of a function? You can use bits to represent.
eg
flag1=0x1
flag2=0x2
flag3=0x4
flag4=0x8
if(flag&flag3){
....
}
黄舟2017-04-17 13:08:13
The significance of bitwise operations is that the operating efficiency is usually several to dozens of times higher than addition, subtraction, multiplication and division. It is often used in algorithms that are very concerned about speed, such as many low-level algorithms. The disadvantage is poor readability and maintainability. For an example, please see this webpage: https://graphics.stanford.edu/~seander/bithacks.html
In addition, using integers to represent sets and using bit operations to perform set operations is also a common usage.
伊谢尔伦2017-04-17 13:08:13
I agree with @__simple, the setting (1) and clearing (0) in the microcontroller can be obtained by operating with another quantity
迷茫2017-04-17 13:08:13
In general, it saves space for calculations and is fast. Examples of applications include
1. Bitmap index. For example, deduplication and query of QQ numbers or phone numbers;
2. Bit mask. Typical ones are linux file permissions;
3. Generate pseudo-random numbers;
4. Gray code
ringa_lee2017-04-17 13:08:13
For example, when writing code for a microcontroller, you need to assign a value to a certain register. It is obviously simpler and more efficient to use bitwise operations.