Question

Here is my code:

int main(){
 unsigned int z = 18;
 z = z>>1;
 std::cout << z << std::endl;
}

I know my result is going to be 9 but I dont understand the line "z = z>>1" What does it do? what does >> mean? I thought it was only used in cin << z; please explain. Thank you

Was it helpful?

Solution

>> is the right bit-shift (a) which shifts all bits in a value right by a given value. For unsigned integers, >> 1 is effectively an integral divide by two.

The value 18 in binary is:

0001 0010
   |   |
   |   +---  2
   +------- 16
            --
            18

Right-shifting that by one bit position (bits "drop off" the right hand side and 0 bits come in from the left) gives you:

0000 1001
     |  |
     |  +--  1
     +-----  8
            --
             9

(a) It is in this particular case. C++ also allows for >> to be used as an operator for classes, such as with std::cin >> myInputVar; which will attempt to read a value from standard input and place it into the myInputVar variable.

OTHER TIPS

It is shift to left for 1 bite of z. For example your z is 18, that is (if int is 2 bytes) 0000 0000 0001 0010 bynary, when you shift it, z becomes 0000 0000 0000 1001 whitch is 9. It actualy work as didide by two. If you have negative falues for example -18, in second complement it is

0000 0000 0001 0010
1111 1111 1110 1101//first complement
1111 1111 1110 1110//second complement

and when you shift it, the sign byte is puted on the top

1111 1111 1111 0111
0000 0000 0000 1000//first complement
0000 0000 0000 1001//second complement

witch is -9.

With this shift to right is easy, search web for shift to left, it is more complicated in case of signed values

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top