Reputation: 17348
I'm just playing with some bitwise operators to refresh myself on how they work. I found something really weird, but perhaps it is just a fundamental misunderstanding of how bitwise operators work.
This program:
#include <iostream>
using namespace std;
int main() {
int base = 16;
cout << (base << 2) << endl;
cout << (base >> 2) << endl;
cout << (base & 0b0001) << endl;
return 0;
}
Outputs this:
64
4
0
The first two I expected, but 0
for the last one seems a bit odd (no pun intended), as I had expected to see 1
. If I do base | 0b0001
I get 17
. It seems like the bit pattern is being appended to the end. Is that what is supposed to happen, or I am missing something here?
I am using G++ v4.8.2.
Upvotes: 0
Views: 232
Reputation: 56547
Remember that base
is 16
, i.e. 10000
in binary. Now AND it with 00001
and see what's happening.
10000 & 00001 = 0
->0 in any base
10000 | 00001 = 10001
-> 17 in decimal
Upvotes: 4