Usage of & in c language

下次还敢
Release: 2024-04-28 09:43:25
Original
1025 people have browsed it

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

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;
Copy after login

Among them, expression1 and expression2 are two integer expressions, result is also an integer variable.

Usage

& operator is usually used in the following scenarios:

  • Check the value of a specific bit: Usage A bitmask (a binary number containing only ones and zeros) is compared with an integer to check the value of a specific binary bit. For example:
if ((number & 0b10000000) != 0) {
  // 最高位为 1
}
Copy after login
  • Set or clear a bit: Use a bit mask and an integer to perform a bitwise AND operation to set or clear the value of a specific bit. For example:
number |= 0b10000000; // 设置最高位为 1
number &= ~0b10000000; // 清除最高位
Copy after login
  • Extract bits: Use a bit mask and an integer to perform a bitwise AND operation to extract the bit value of a specific bit. For example:
bit_value = number & 0b00000001; // 提取最低位
Copy after login
  • Mask non-zero values: Use the & 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
}
Copy after login

Note: The

  • & operator cannot be used with floating point numbers.
  • & operator has a higher priority than , -, *, / operators, but lower than !=, ==, <, > and other comparison operators.

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template