Bitwise operation

Bitwise Operation

Intro

In digital computer programming, a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast and simple action, directly supported by the processor, and is used to manipulate values for comparisons and calculations.

It can be divided into:

Bit addressing operator:

& And

| Or

^ XOR

~ Not

Bit shifting Operator:

<< Shift to left

>> Shift to right

Operator Instructions

&

Base on the name “and”. It is easy for us to know that: if 1 is true and 0 is false. Only a and b are both true, the statement is true.

0&0 0
0&1 0
0&1 0
1&1 1

|

“Or” is pretty similar to “and”. As long as a or b is true, the statement is true.

0|0 0
0|1 1
0|1 1
1|1 1

^

“Xor” becomes a little complicated. That is: a and b must happen at the same time, else they won’t happen. Only both happen or none happen are true.

0^0 1
0^1 0
0^1 0
1^1 1

~

“Not”, easy body. So true becomes not true = false. False becomes not false = true.

<<

“Shift to the left”

Take a<<2 for example. It is switch a into binary number and move to the left by 2.

$\therefore$ 100<<2, (100)2=1100100<<2=110010000=400. We can tell that it is equal to 100*2^2^.

>>

“Shift to the right”

Take a>>2 for example. It is switch a into binary number and move to the right by 2.

$\therefore$ 100<<2, (100)2=1100100<<2=11001=25. We can tell that it is equal to 100/2^2^.

Welcome to my other publishing channels