+ 1
What does c++ code do ??
I've seen this code before but never ask me what it really does. i just know it's a bitwise operator but what it does behind de scene, is in fact my question?, i hope someone can explain me. int main() { int integer = 5; if (integer & 0x3) { cout << "surprise"; } return 0; }
4 Answers
+ 10
In this code you have used an hexadecimal number 0x03 which is 3 in decimal.
0x is representing the hexadecimal digit if you do 0x10 then the digit will be 16 in decimal
And integer value is defined as 5 so 5&3 two zero integer will return true so output is come as "surprise"
If you do 0x00 then the and operation failed as any value which generate 0 will become make condition false
+ 7
Dec | Binary |
5 | 0101 |
3 | 0011 |
--------------------- &
1 | 0001 |
In C/C++ any non zero integral value is considered true when the value is treated and/or used as logical expression (as if it were a boolean value), or as part of a logical expression.
From the bitwise AND operation shown above, we can see that since `5 & 3` yields 1 (which is considered true), that's why the `if` block was executed. Had the operation yield zero (false logically), the `if` block would not have been executed.
There's a bitwise operators intro available in the Learn section. Pay a visit there to get a better understanding đ
https://www.sololearn.com/learn/4070/?ref=app
+ 3
The "&" is called the bitwise AND operator. Also a number starting from 0x is a hexadecimal number.
So now convert both the numbers to binary and do & operation on them.
This code will give you "not surprised" because the & of 5 and 8 will give 0. So the if condition fails and the else is executed.
int integer = 5;
if (integer & 0x8) {
cout << "surprise";
}
else
cout << "not surprised";
+ 2
No one explained what the & does "behind the scene" yet, apart from saying it's the bitwise and operator.
The & operator looks through the bits of 2 numbers and generates a new number.
If both bits are 1, the resulting bit is also 1. Any other combination is a 0.
Example:
5 00000101
&
3 00000011
=
1 00000001
91 01011011
&
36 00100100
=
00 00000000
It is often used as a bitmask:
https://en.m.wikipedia.org/wiki/Mask_(computing)