Hi srini, this question has been given in the java rule round up game. and the ans they have given is negative.

sri rallapalli
Ranch Hand

Joined: Mar 15, 2005
Posts: 88

posted Mar 24, 2005 00:27:00

0

Hi srini, this question has been given in the java rule round up game. and the ans they have given is negative. I dont know, how this becomes negative.

Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228

posted Mar 24, 2005 01:48:00

0

This code wont compile.

Can you just paste the code you saw in round up game.

The concept goes this way : Then when you are using the signed right shift operator ( >> ) the value of sign bit is maintained . The new bit added after the shift in the left side will be the same as before ( to be more clear the value of sign bit is maintained as such.)

PS : you can use a Pencil like icon for editing the previous post instead creating a new . [ March 24, 2005: Message edited by: Srinivasa Raghavan ]

Notice that the byte is starting with 1 (consider it as signed byte). x is 10110011( it is -77) After x>>2, move from the left to 2 bits forward, then the two 1's in the rightmost side will be lost. It is like this

--101100, the two emply spaces in the left will be filled with 1. So the result of x after x>>2 is 11101100. You would be confused why the high order bits(left most bit in a byte is called high order bit) r filled with 1? When you are shifting right, the leftmost bits exposes by the right shift are filled in with the previous contents of the top bit, and the as many number of bits in the right will be discarded.This is called sign extension and serves to preserve the sign of negative numbers when u shift them right. This happens only in right shift but not in left shift.

Finally coming to ur example 10110011 is -77 >>2 11101100 is -20 after x>>2 -77 has become -20.

cheers, Kranthi.

Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228

posted Mar 24, 2005 02:44:00

0

So the following steps are followed on shifting a negative number 1. Find 2's compliment, 2. Find 1's compliemt for the result 3. Then Shift depending upon the shift operator .

Is that right ?

Srinivasa Raghavan
Ranch Hand

Joined: Sep 28, 2004
Posts: 1228

posted Mar 24, 2005 02:46:00

0

Kranthi , Good i got it.

sri rallapalli
Ranch Hand

Joined: Mar 15, 2005
Posts: 88

posted Mar 24, 2005 04:04:00

0

Hi Kranthi, is this is the way for all the negative numbers? like whether it is an int or short or long.

when we right shift a negative number, what ever the last bit, whether it is 0 or 1, the same will be replaced for the left most bits right.

am i correct kranthi?

Kranthi Kumar
Greenhorn

Joined: Jan 14, 2005
Posts: 11

posted Mar 24, 2005 11:27:00

0

Hi Sri,

Yes, what ever the int type it is, the high order bit is replaced by the previous top bit bit. either it is 0 or 1.This is to preserve the sign of the number.