Home > Backend Development > C#.Net Tutorial > Usage of ~ in c language

Usage of ~ in c language

下次还敢
Release: 2024-05-02 18:24:16
Original
1097 people have browsed it

The ~ operator in C language is used for bitwise inversion of binary numbers, that is, 0 becomes 1 and 1 becomes 0. Specific applications include negating bit masks, detecting binary bits, creating one's complement codes, and generating one's complement codes.

Usage of ~ in c language

Usage of ~ operator in C language

The role of ~ operator

~operator is a bitwise negation operator in C language. It inverts each bit of a binary number, i.e. 0 becomes 1 and 1 becomes 0.

Syntax

<code>~expression</code>
Copy after login

where expression can be any integer type data.

Operation result

~The operation result of the operator is an integer of the same type as expression, and every bit in its binary representation is inverted.

Application scenarios

~Operators are mainly used in the following scenarios in C language:

  • Reverse bit mask :Inverting a bitmask produces a mask that is the opposite of the original bitmask. For example: ~0x0F is generated as 0xF0.
  • Detecting binary bits: By performing the ~ operation on a number and bitwise ANDing it with another number, you can check whether a specific binary bit of the number is 1. For example: x & ~0x08 checks whether the 3rd bit of x is 0.
  • Create one's complement code: For negative numbers, the ~ operator can generate its one's complement code. For example: ~(-5) generates 4.
  • Generate one's complement: For negative numbers, the ~ operator can generate its complement. For example: ~(-5) is generated as 3.

Example

<code class="c">#include <stdio.h>

int main() {
    int x = 0x12;

    printf("~x = %x\n", ~x);   // 输出: 0xED
    printf("~x & 0x08 = %x\n", ~x & 0x08);  // 输出: 0x00 (检查 x 的第3位是否为0)

    return 0;
}</code>
Copy after login

Note:

~ operator has higher precedence than bitwise AND (& ) and bitwise OR (|) 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template