programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# How to use shift operators?

Ranch Hand
Posts: 79
Hi,
I am preparing for SCJP exam, i am unable to solve the questions related to shift operators, kindly help me, this is most urgent.
thank you.

------------------
JSP

Greenhorn
Posts: 16
The shift operators are designed to move bits around in a byte. For instance, 1 is represented as 0000 0001 in binary. Doing a shift left on this will move all the bits one place to the left, resulting in 0000 0010, or the number 2. The number 3 would be shown as 0000 0011. A shift left of one place on this returns 0000 0110, or the number 6. Hence, a left shift of one place effectively doubles a number.
Does this answer your question? Maybe if you posted the specific questions from your SCJP exam, we could be of more help.
- Don

Ranch Hand
Posts: 79
Thank you Don, i have understood the left shift operators, in addition to this i want to know about right shift and unsigned shift operators, and is there any short-cut formula to solved these questions, because i have seen, some of the questions are very cryptic and lengthy. looking forward for a nice solution.
JSP
------------------
JSP

"The Hood"
Sheriff
Posts: 8521
Right shift is just the opposite of left shift. If you have a value 0000 1111 (15) and you right shift, it will become
0000 0111. The rightmost digit drops off and you are left with 7.
If you start with a negative number (the leftmost digit is a 1)
1000 1111 and right shift (this is a signed shift) it will become 1100 0111. The leftmost bit will retain the previous value.
If you do an unsigned right shift you would get 0100 0111 (the leftmost bit is always 0 no matter what it started as.
There is not really any short cut. It is straight forward, it's just that negative binarys are kind of messy to work with.

Ranch Hand
Posts: 81
Is there any advantage using the shift operators as opposed to regular arithmetic operators if regular operators are possible. For example, left shift is the same as multiplying by 2. Does using the left shift operator give better performance?

Cindy Glass
"The Hood"
Sheriff
Posts: 8521
Well, if you are stuffing lots of code into a teeny tiny little chip, it is a great way to get lot's done with little space. It's amazing the clever things some people think up to use bit switching.
Myself, I try to avoid it.

Ranch Hand
Posts: 347
Anyone wanting to know more about shifting and bits might be helped by reading the campfire story here:
http://www.javaranch.com/campfire/StoryBits.jsp