# Thread: Unsigned right shift operator - clarification requested.

1. Member
Join Date
Jan 2017
Posts
5
Rep Power
0

## Unsigned right shift operator - clarification requested.

For the below program, please let me know why the bit pattern output is different for the second and the third for-loop even though the total number of unsigned right shift on -1 is the same (i.e 32 shifts) in both cases.

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
14

## Re: Unsigned right shift operator - clarification requested.

OK, first, please don't post images. Post the code in between code tags. See BBCodes at bottom of post for more info.

byte i = -1;
i >>>= 32; // this does nothing because shifts are done mod 32 so 32 mod 32 = 0.

However,
i >>>=1;

The above is still -1 because shifts are done as integers (even though you are shifting the sign bit).
so now i is equal to Integer.MAX_VALUE. But it is reassigned to a byte. The low order 8 bits are assigned
which makes it a -1 again.

To shift a -1 byte to the right 1 bit you must do the following
i >>>= 25;

That converts it to an int, shifts right 25 bits get 127 and
then assigns it back to a byte as 127.

So the key thing to remember is that before a byte or a short
is shifted, it is converted to an integer first, then shifted and converted
back to the original type. So any conversion rules from byte or short to
int are then applied, including sign extension.

Longs are treated normally.

Regards,
Jim
Last edited by jim829; 01-30-2017 at 04:45 PM.

3. Member
Join Date
Jan 2017
Posts
5
Rep Power
0

## Re: Unsigned right shift operator - clarification requested.

Hello Jim, thanks for your clear explanation on this.
I will make sure to use BB codes next time.

Kind Regards,
Bala

4. Member
Join Date
Jan 2017
Posts
5
Rep Power
0

## Re: Unsigned right shift operator - clarification requested.

Hello Jim, thanks for your clear explanation on this.
I will make sure to use BB codes next time.

Kind Regards,
Bala

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•