+ 1

# Help me plz

Who can me explain the purposes, where we can use bit shifting ( << >>) and bitwise operations (&, |, ~, ^) in C

4 ответов

+ 5

The purpose of bit shifting is to shift the binary values to either left or right accordingly by a specified number of positions.
The bitwise operators like & is bitwise AND it will be true when both are true otherwise false. In addition | is bitwise OR it will be true when either is true otherwise false. Furthermore ~ is bitwise Not it will be true when it is false and false when true like vice versa. In conclusion ^ is bitwise XOR where when same then false and if different true.
You can check out below for detailed info along with examples
https://www.geeksforgeeks.org/left-shift-right-shift-operators-c-cpp/
https://www.geeksforgeeks.org/bitwise-operators-in-c-cpp/

+ 2

Виталий Янчик since computers conceptually work in binary, it is self-evident that we need operators that can manipulate bits.
In the Community section of Sololearn you can learn more about how and why to use the bitwise operators.
https://www.sololearn.com/learn/11804/?ref=app

+ 2

Bit Shifting (<<, >>):
Left Shift (<<) – Shifts all bits to the left, which is equivalent to multiplying the value by a power of 2. For example, 5 << 1 (shifting 5 left by 1 bit) results in 10, as it multiplies 5 by 2.
Right Shift (>>) – Shifts all bits to the right, which is equivalent to dividing the value by a power of 2. For example, 10 >> 1 (shifting 10 right by 1 bit) results in 5.
Bitwise Operations (&, |, ~, ^):
AND (&) – Compares each bit of two numbers and returns 1 if both bits are 1, otherwise returns 0. It’s often used for masking bits.
OR (|) – Compares each bit of two numbers and returns 1 if at least one of the bits is 1. It’s used for setting bits.
NOT (~) – Flips all the bits of the number (0s become 1s and vice versa).
XOR (^) – Compares each bit of two numbers and returns 1 if the bits are different, and 0 if they are the same. Often used for toggling bits or finding differences between numbers.

+ 1

Bitwise operations are mostly used for compiler optimizations.