I am looking at some code that casts a Java long to a Java int, where the long may have some bits set in the high half (the high 32 bits), possibly including the sign bit. I have been unable to find documentation of exactly what the compiler or JVM does.

The code that I am looking at appears to assume that what happens is that the high half is just discarded, with no special concern about sign bit or whatever. As the code does appear to work correctly, I guess that this assumption is correct, but I'd be happier if someone could point me to documentation.

I am also a bit confused about the signed and unsigned right-shift operators. Here's my understanding, for you to correct, if it is wrong. The unsigned one (>>> ) shifts all 64 bits of a long to the right, filling in with zeros at the high end (and hence possibly changing a negative to a positive). The signed one (>> ) shifts the low 63 bits of a long to the right, filling in with zeros at the high end of the 63 bits, but always leaves the highest, sign bit alone.

The code that I'm looking at is actually trying to get two Java int values that represent the high and low 32 bits of a Java long, respectively. It goes something like this:

[ October 18, 2004: Message edited by: Peter Chase ]

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.

The signed one (>> ) shifts the low 63 bits of a long to the right, filling in with zeros at the high end of the 63 bits, but always leaves the highest, sign bit alone.

NO - the high bit is shifted right but preserved, no zero fill with >> Try it yourself - the Int and Long methods toHexString() will help you visualize what happens. Bill

Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970

posted

0

Originally posted by William Brogden:

NO - the high bit is shifted right but preserved, no zero fill with >>

Ah, yes, that does make sense when I think about it. That allows right shift to be used for dividing by powers of two, for positive and negative numbers, doesn't it? Which is presumably why it's called "signed" right-shift.

In the code that I was looking at, it does not actually matter what happens to the high 32 bits, during right-shift, so long as the assumption about casting long to int just dropping the high bits is true - which you've confirmed. Though, where did you find that information, or just by experience?