Shift and bitwise operator

i m unable to understand how the shift operator(>>,<<) and bitwise operator (&, |, ^) works. please explain its functioning

Hey @himanshigupta579 we do know that essentially all the numbers are written in bits.

left shit ( << ) it just shift the entire number left by given bits, or adds given number of bits behind so if number is 101 and we left shift it by one it become 1010, similarly right shift shifts towards right so if the number is 101 and it is right shifted by 1 it become 10

bitwise operators like &, ^, | works on 2 numbers lets say we have two numbers a and b they’ll convert the given numbers into bits and compare the corresponding bits so say if a = 5 and b = 3 they will convert a into 101 and b into 011 i.e their binary representation and perform the given operation between 1 and 1, 0 and 1, 1 and 0 and the result of the operation is governed by the operation type
The & (bitwise AND) in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.
The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.

I got the bitwise operators. Left and Right shift operators are not yet cleared. I wanted to ask as told in “Using operators” that if x=5 and i do x<<2 , the x will be multipiled with 2^2 i.e 4 so ans will be 20. And if y=7 and i do y>>1 , y will be divided by 2 . Is that so?

yes if you do x<<2 then x would be multiplied by 2^2, and if you do y>>1 then y will be divided by 2.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.