Bitwise Qns

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
using namespace std;

int defaultPara (int x = 100, int y = 200, int z = 300);
int staticVar();

int main ()
{
	int n = defaultPara (10, 20, 30);
	int m = defaultPara (10, 20);
	
	cout << n << endl; //64  Working: 10 + 20 + 30 + 4 = 64
	cout << m << endl; //338  Working: 10 + 20 + 300 + 8 = 338
	cout << staticVar () << endl; //16     when x = 8, staticVar() = 8 * 2
	
	cout << (n >> 3) << endl; //8
	cout << ((n & m) << 1) << endl;  //128
	
	return 0;
}

int defaultPara (int x, int y, int z)
{
	return x + y + z + staticVar();
}

int staticVar()
{
	static int x = 2;
	x *= 2;
	
	return x;
}

I am wondering what will be the workings for

cout << (n >> 3) << endl; //Is it 64/3?
cout << ((n & m) << 1) << endl; //How about this?
Last edited on
n >> 3 is a rightshift by three (n divided by 8).
& is the bitwise AND.
<< 1 is a leftshift by one.
What is n? Why divided n/8?
n is a variable. The content of that variable is used.

You're working in base 2 (binary), so for each right-shift, you're dividing by 2. You do it three times, so that's dividing by 2x2x2, 8.
Tks. Ok, I got the answer now for (n>>3).
64/2=32
32/2=16
16/2=8(Ans)

For ((n & m) << 1), do I convert n & m to binary first then compare them using &?
Yes, you can understand it this way.
Your example:
64 & 338 = 64

  001000000  (64)
& 101010010  (338)
= 001000000  (64)


In your code it's also leftshiftet by 1, which means *2

(64 & 338) << 1

64 << 1 = 64*2 = 128
Tks kbw & MaikCAE! I am grateful to your help.

Cheers,
makan007
Topic archived. No new replies allowed.