Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the operation methods of C language bits?

Shulou Source: shulou.com Published: 2022-06-02 12:13:17 10月03日 Update

This article mainly explains "what are the C language bit operation methods", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let Xiaobian take you to learn "what are the C language bit operation methods"!

bit operating

Bit operations are unary and binary operations on bit patterns or binary numbers in programming. On many older microprocessors, bit arithmetic

Slightly faster than addition and subtraction, bit operations are usually much faster than multiplication and division. In modern architecture, this is not the case: bitwise operations are usually faster

Same as addition (still faster than multiplication).

bitwise operators

Negation (~) is a unary operator that performs a logical inversion on each bit of a binary number. Make the number 1 0 and 0 1.

by position or (|Processing two binary numbers of the same length, as long as one of the two corresponding binary bits is 1, the result value of the bit is 1.

Bitwise XOR (^) performs a logical bitwise XOR operation on each bit of a bitwise or binary number in an equal long binary pattern, resulting in a bit being 1 if it is different and 0 otherwise.

Two binary numbers of the same length are processed by bits and (&), and the two corresponding binary bits are both 1, and the result value of this bit is 1, otherwise it is 0.

shift

Shift is a binary operator used to shift each bit of a binary number in one direction by a specified bit, with the overflow discarded and the empty bit filled in with a specified value. In C-like languages, left shift is represented by two less-than symbols.

A logical shift, whether left or right, is a zero.

Arithmetic shift to ensure that the sign bit does not change (logical left shift complement 0, logical right shift to see the sign bit).

For example: 110110011 is-10110011 The first 1 before is the sign bit

Then 110110011 shifted one bit to the right should be 111011001.

Here are some simple programming problems for bit operations

Swap the values of two integers without extra variables

#includeusing namespace std;int fun1(int a,int b){ int tmp=a-b; tmp>>=(sizeof(int)*4-1); if(tmp) return b; return a;}int main(){ int a=-134,b=98; cout

Tags: Operation binary two logic method language symbol same integer result operator no binary content pattern part length processing learning different Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia MariaDB macOS Redmi Shulou Information