tags:

views:

661

answers:

4

I have an Int64 value, but I only need the lower 32 bits. Thus I want a quick way to get the Int32 value from the lower 32 bits of the Int64 value.

Thanks

+1  A: 

You didn't specify the language, but in many, all you need to do is cast it to an Int32. The top bits will be discarded.

Steven Sudit
A: 

Basically you will want to shift the lower 4 bytes into a 32-bit int.

The discussion in this forum may be of use: http://forums.sun.com/thread.jspa?threadID=764603

James Black
Interesting Java reference, but I don't think shifting is needed.
Steven Sudit
I have had bad luck at times (mainly with C/C++) with just casting, so I have found shifting to be the best bet, as it gives control and is very quick. Most of my converting like this has been from int to unsigned byte though. :)
James Black
+4  A: 

Do something like this:

long tempLong = ((yourLong >> 32) << 32); //shift it right then left 32 bits, which zeroes the lower half of the long
int yourInt = (int)(yourLong - tempLong);

This may not be the most compact way to do it, but it seems to be the most readable to me. The following code will extract the high half of the long:

long tempLong = (int)(yourLong >> 32);
RCIX
Depending on how good the compiler is at optimizing, your first code sample may be substantially slower than just casting. Personally, I don't find it particularly clear, either.
Steven Sudit
A: 

If you assign a int64 value into a int32 value, the compiler will automatically do that for you
(as Steven Sudit mentioned):

int64 val64 = ...;
int32 val32 = ...;
...

val32 = val64; // get the low 32 bits
// or
val32 = (val64 >> 32); // get the high 32 bits

and because the compiler may display warnings you can specify the cast

val32 = (int32)val64;
Nick D