What does >> do in Java?
Okay, I tried looking up what >> , or shift means, but it’s way over my head as this site explains it: http://www.janeg.ca/scjp/oper/shift.html
What would the explanation be, if talking to a kid?
4 Answers 4
Computers are binary devices. Because of this, numbers are represented by a sequence of 1s and 0s.
Bitshifting is simply moving those sequences of 1s and 0s left or right.
So all the >> operator does is shift the bits towards the right one bit.
Consider the number 101:
The least significant bit in this case was truncated. Obviously the devil’s in the details, but that’s all there is really to it.
The operator does the opposite operation:
In this case, the most significant bit was truncated since I used only 8-bits. If the number had more bits, however:
So you may get different numbers depending on how many bits and the data types associated with those bits you’re dealing with.
Addendum: If you’re wondering how binary works, think about how the decimal number system works. Consider the number 5287. It can be written like this:
But you can also write it out like this:
Which you can then write out like this:
The above equation explains why the decimal number system is sometimes called the base-10 system. The decimal number system employs the use of 10 digits (0-9). Notice how the exponents correspond to digit position.
The binary number system, or the base-2 system, is the exact same thing but with the number two as the base of the exponents, and employing only two digits: 0 and 1.