Practical Tips on Bit Operators

Foreword
Bit operators are operators used to operate binary data. Bit operators have the advantages of high efficiency and simplicity, which can improve the efficiency of the code. Today I will share with you the skills of using bit operators.
Insert image description here

Tip
1, multiply by 2, divide by 2, multiply by 10.
First of all, we know that the << operator can shift the binary of our data one bit to the left, so that the result will be multiplied by 2 (within a certain range).

int a = 10;
a <<= 1//现在a=20

Then the >> operator can shift the binary of our data to the right by one bit and divide the result by 2.

int a = 10;
a >>= 1//现在a=5

We know that a * 10 = a * 2 + a * 8, so can we write *10 like this?

int a = 10;
a = a<<1+a<<3//现在a=100 

Determining odd and even numbers
We can use the & operator to determine odd and even numbers.

int a = 10;
int b = 11;
//a&1=0,b&1=1,也就是说让一个数与1&结果是1则说明是奇数反之为偶数

Swap values
​​We know a^a=0, so we can use this feature to swap values

int a = 10;
int b = 20;
a^=b;// a = a^b
b^=a;//b = a^b^b = a
a^=b;//a = a^b^a = b
//此时a = 20,b = 10

Determine whether they are equal.
When two numbers are the same, that is, a = b, then a ^ b = a ^ a = 0.

int a = 10;
int b = 10;
if(a^b)
printf("不相等");
else
printf("相等");

Conversion between 0-9 and '0'-'9'.
For example, if we want to change 1 to '1', we usually write like this

int a = 1;
char b = 1+'0';

But we can still write this

int a = 1;
char b = a^48;

In the same way, if we want to turn '1' into 1, we can also write it like this

char a = '1';
int b = a ^ 48;
//此时b是1

The
above are the tips for using bit operators. People who have never seen it will definitely be dumbfounded on the spot. If you think the blogger’s words are good, please give the blogger a follow, like, and favorite~ See you next time!

Guess you like

Origin blog.csdn.net/Tokai___Teio/article/details/135310797