Home > Article > Backend Development > Usage of & in c language
The & operator in C language is used to perform a bitwise AND operation, comparing each bit of two binary numbers. If they are the same, they will be 1, and if they are different, they will be 0. The uses include: ① Check a specific bit value; ② Set or clear a bit; ③ Extract a bit value; ④ Mask non-zero values. The priority is higher than operators such as ,-,*,/ and lower than comparison operators.
Usage of & in C language
In C language, the & operator is a bitwise operator, Used to perform bitwise AND operations.
Bitwise AND operation
The bitwise AND operation compares each bit of two binary numbers. If both bits are 1, the result is 1; otherwise , the result is 0.
Grammar
result = expression1 & expression2;
Among them, expression1
and expression2
are two integer expressions, result
is also an integer variable.
Usage
& operator is usually used in the following scenarios:
if ((number & 0b10000000) != 0) { // 最高位为 1 }
number |= 0b10000000; // 设置最高位为 1 number &= ~0b10000000; // 清除最高位
bit_value = number & 0b00000001; // 提取最低位
&
operators to combine an integer with a non-zero value (such as -1) Bitwise AND operation can mask out non-zero values. This can be used to check if a value is non-zero. For example: if (number & -1) { // number 不为 0 }
Note: The
The above is the detailed content of Usage of & in c language. For more information, please follow other related articles on the PHP Chinese website!