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

# shiftoperators

Suhita Reddy
Ranch Hand
Posts: 60
Hi,

wht is the diff b/w shift operators <<,>>,>>> operators?
I know tht 2<<2 i.e 2*2power2
2>>2 i.e 2/2power 2
2>>>2 wht it gives

Regards
Suhita

Ken Blair
Ranch Hand
Posts: 1078

Ken Blair
Ranch Hand
Posts: 1078
Actually that may not make the distinction clear. When using the >> it will perform an arithmetic shift, that is to say the left bits will be filled with sign bit. When using >>> it will perform a logical shift and the left bits will be filled with zeros. The distinction becomes important when dealing with numbers that are signed, in this case specifically negative numbers.

Take a look at this example:

You'll notice that with 'a' there is no difference because it is positive and both fill the left side with zeros. With 'b', however, the distinction becomes very noticeable because rather than filling the left side with the sign bit it fills it with zeros. With both >> and >>> a will become 3 whereas with b the >> will make it -4 and >>> will make it 1073741820. Big difference.
[ July 06, 2006: Message edited by: Ken Blair ]

Shaan Shar
Ranch Hand
Posts: 1249
Originally posted by Ken Blair:
Actually that may not make the distinction clear. When using the >> it will perform an arithmetic shift, that is to say the left bits will be filled with sign bit. When using >>> it will perform a logical shift and the left bits will be filled with zeros. The distinction becomes important when dealing with numbers that are signed, in this case specifically negative numbers.

Take a look at this example:

You'll notice that with 'a' there is no difference because it is positive and both fill the left side with zeros. With 'b', however, the distinction becomes very noticeable because rather than filling the left side with the sign bit it fills it with zeros. With both >> and >>> a will become 3 whereas with b the >> will make it -4 and >>> will make it 1073741820. Big difference.

[ July 06, 2006: Message edited by: Ken Blair ]

Additional Input in Ken's Message is if you really want to get through hand on in Bitwise Operators. This will give you a more clear understanding.

Bitwise Operators.....

Hope it helps you.

 It is sorta covered in the JavaRanch Style Guide.