Can I convert long to int?
Solution 1
Just do (int)myLongValue
. It'll do exactly what you want (discarding MSBs and taking LSBs) in unchecked
context (which is the compiler default). It'll throw OverflowException
in checked
context if the value doesn't fit in an int
:
int myIntValue = unchecked((int)myLongValue);
Solution 2
Convert.ToInt32(myValue);
Though I don't know what it will do when it's greater than int.MaxValue.
Solution 3
Sometimes you're not actually interested in the actual value, but in its usage as checksum/hashcode. In this case, the built-in method GetHashCode()
is a good choice:
int checkSumAsInt32 = checkSumAsIn64.GetHashCode();
Solution 4
The safe and fastest way is to use Bit Masking before cast...
int MyInt = (int) ( MyLong & 0xFFFFFFFF )
The Bit Mask ( 0xFFFFFFFF
) value will depend on the size of Int because Int size is dependent on machine.
Solution 5
A possible way is to use the modulo operator to only let the values stay in the int32 range, and then cast it to int.
var intValue= (int)(longValue % Int32.MaxValue);
Related videos on Youtube
ShigaSuresh
Updated on May 13, 2020Comments
-
ShigaSuresh almost 4 years
I want to convert
long
toint
.If the value of
long
>int.MaxValue
, I am happy to let it wrap around.What is the best way?
-
T.J. Crowder about 13 years"Though I don't know what it will do when it's greater than int.MaxValue" It will throw an
OverflowException
, which is exactly what the OP doesn't want: msdn.microsoft.com/en-us/library/d4haekc4.aspx -
T.J. Crowder about 13 yearsFor anyone else who had the same question I did: Note that discarding the MSBs can have an effect on the sign of the result. With the above,
myIntValue
can end up negative whenmyLongValue
is positive (4294967294 => -2
) and vice-versa (-4294967296 => 0
). So when implementing aCompareTo
operation, for instance, you can't happily cast the result of subtracting onelong
from another to anint
and return that; for some values, your comparison would yield an incorrect result. -
TamusJRoyce over 12 yearsTest if myValue > Integer.Max before running the convert, if you need to do other processing when myValue > Integer.Max. Convert.ToInt32(myValue) will overflow (no exception, I believe) otherwise. This method works in VB.NET as well.
-
mmx over 12 years@Chris:
new Random()
usesEnvironment.TickCount
under the hood; no need to seed manually with clock ticks. -
Caramiriel about 10 yearsIt's been a while ago since this answer was given, though I want to mention that the hashcode implementation might differ between .NET versions. This might not actually be happening, but there is no guarantee that this value is the same between different application runs/appdomains.
-
Richard June over 9 yearsWhile (int) is valid, Convert is a better answer. Better to have weird exceptions than weird data.
-
Glenn Slayden about 7 yearsThe default context is
unchecked
, so unless you've explicitly changed it, then theunchecked
keyword (as shown in this answer and @ChrisMarisic's comment, etc.) is not needed, andint myIntValue = (int)myLongValue
is exactly equivalent. However do note that regardless of whether you use theunchecked
keyword or not, you're getting the non-mathematical rude truncation behavior described by @T.J.Crowder where the sign can flip in some overflow cases. The only way to truly ensure mathematical correctness is to use thechecked(...)
context, where those cases will throw an exception. -
ruffin about 7 years@RichardJune Um, no? The OP here explicitly says, "If the value of long > int.MaxValue, I am happy to let it wrap around." I can see arguing your statement in general, but in this specific case, no,
Convert
is not good. -
Sergey about 7 years
if (value > Int32.MaxValue)
return Int32.MaxValue;
else
return Convert.ToInt32( value );
-
ToolmakerSteve about 6 yearsNeed to decide what you want to happen when the result will either overflow, or become a negative number. What you show will still overflow, IIRC, because you are letting the sign bit through. [As mentioned in another answer, in
unchecked
context you won't get an overflow - but you don't need to mask inunchecked
to avoid the overflow, so a solution is only needed inchecked
context.] Example for 16-bits. Signed 16-bits holds (-32768, 32767). Masking with 0xFFFF allows value up to 65535, causing overflow, IIRC. Could mask to avoid sign bit, 0x7FFF or 0x7FFFFFFF, if want positive only. -
ToolmakerSteve about 6 yearsTo add to what @Caramiriel is saying: if using as a temporary hashcode, during your current app session, then
GetHashCode
is an appropriate choice. If you are after a persistent checksum - a value that will be the same when you run your app later, then don't useGetHashCode
, as it is not guaranteed to be the same algorithm forever. -
Jeppe Stig Nielsen about 5 yearsThis would clamp the
longValue
to the nearest representableint
if the original value is to huge. But it lacks the same treatment of too negative inputs, which would lose the most significant bits instead; you would need to compare toInt32.MinValue
also. The original poster did not seem to want clamping, though. -
G. Goncharov over 4 yearsIMHO sometimes better to get exception than wrong value, which Int32.MaxValue would be...
-
GuiRitter over 3 yearsThis worked best for me, as all other attempts to bit mask transformed 281474976710656 (2^48) to 0.
-
ToolmakerSteve over 2 years@Sergey - if that is what you want to do, then don't forget MINUS numbers:
return value < Int32.MinValue ? Int32.MinValue : (value > Int32.MaxValue ? Int32.MaxValue : (int)value);
-
ToolmakerSteve over 2 yearsTo clamp negative values also, do
(int)Math.Max(Int32.MinValue, Math.Min(Int32.MaxValue, longValue))
. However I find the equivalent stackoverflow.com/a/58011064/199364 easier to understand. -
ToolmakerSteve over 2 years@GuiRitter - Certain large values will still become 0. (Any multiple of MaxValue). Consider instead
(int)(longValue > Int32.MaxValue ? (longValue % Int32.MaxValue) + 1 : longValue)
. Similar logic can be added for negative values:(int)(longValue < Int32.MinValue ? (longValue % Int32.MaxValue) - 1 ? (longValue > Int32.MaxValue ? (longValue % Int32.MaxValue) + 1 : longValue))