Long->Int Typecasting

Status
Not open for further replies.

dknguyen

Well-Known Member
Most Helpful Member
I have some calculations (mainly the time in seconds) where the lengths of time I am working with need to be stored as long. BUt after some calculations I have to load the result into a 16-bit configuration register.

I want to only use the most significant two bytes of the long and load them into this register (so I can preserve the meaning but lose the resolution. Obviously I can't use the bottom two LSBs because I would lose the meaning of the number entirely)

But if I go:

some integer = some long

to use the implicit typecast, does which half does it take? Does it even work properly?
 
Shift the number to get rid of the unwanted low order bits.
int16 aInt;
int32 aLong;

aInt = (int)(aLong >>16);
 
Ahh, that's the operation for bit shift. Cool. Thanks.

BUt I still wonder what happens if you try and typecast a long to an int. Int to long is no problem since long contains int...but I don't know about the other way.
 
dknguyen said:
Ahh, that's the operation for bit shift. Cool. Thanks.

BUt I still wonder what happens if you try and typecast a long to an int. Int to long is no problem since long contains int...but I don't know about the other way.

As Mike said.
If the value in the larger type does not fit the smaller, the top bits are lost.

The int16 value 0x1234 will become 0x34 if the int16 is cast to a char.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…