Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to get the low 32 bit of a int64 as int32

Tags:

int64

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

like image 747
qingsong Avatar asked Sep 19 '09 05:09

qingsong


People also ask

Is Int64 faster than Int32?

Int32 will be equally as efficient on all x86, x64, and IA64. On an x64 and on an IA64 both Int32 and Int64 are equally as efficient. On an x86 Int32 will be more efficient than an Int64.

How do you create a 32 bit integer?

You can declare 8-, 16-, 32-, or 64-bit integer variables by using the __intN type specifier, where N is 8, 16, 32, or 64. The types __int8 , __int16 , and __int32 are synonyms for the ANSI types that have the same size, and are useful for writing portable code that behaves identically across multiple platforms.

What is 32 bit and 64 bit integer?

A 32 bit Signed Integer can house a number from −2,147,483,648 to 2,147,483,647 Unsigned: 0 to 4,294,967,295. A 64 bit Signed Integer can house a number from −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Unsigned: 0 to 18,446,744,073,709,551,615.

What is the value of Int64?

Int64 is an immutable value type that represents signed integers with values that range from negative 9,223,372,036,854,775,808 (which is represented by the Int64. MinValue constant) through positive 9,223,372,036,854,775,807 (which is represented by the Int64. MaxValue constant.


2 Answers

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;
like image 194
Nick Dandoulakis Avatar answered Oct 17 '22 16:10

Nick Dandoulakis


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);
like image 11
RCIX Avatar answered Oct 17 '22 16:10

RCIX