ins*_*ite 136 c# int types type-conversion long-integer
我想转换long
为int
.
如果long
> 的值int.MaxValue
,我很乐意让它环绕.
什么是最好的方法?
Meh*_*ari 211
做吧(int)myLongValue
.它将完全按照您的需要(丢弃MSB并使用LSB)在unchecked
上下文中执行(这是编译器的默认设置).它会扔OverflowException
在checked
上下文中,如果值不适合的int
:
int myIntValue = unchecked((int)myLongValue);
Run Code Online (Sandbox Code Playgroud)
Max*_*ing 32
Convert.ToInt32(myValue);
Run Code Online (Sandbox Code Playgroud)
虽然我不知道当它比int.MaxValue更大时会做什么.
rea*_*art 15
有时您实际上并不对实际值感兴趣,而是将其用作校验和/哈希码.在这种情况下,内置方法GetHashCode()
是一个不错的选择:
int checkSumAsInt32 = checkSumAsIn64.GetHashCode();
Run Code Online (Sandbox Code Playgroud)
小智 8
一种可能的方法是使用模运算符只让值停留在 int32 范围内,然后将其强制转换为 int。
var intValue= (int)(longValue % Int32.MaxValue);
Run Code Online (Sandbox Code Playgroud)
小智 7
安全和快速的方法是在演员之前使用Bit Masking ...
int MyInt = (int) ( MyLong & 0xFFFFFFFF )
Run Code Online (Sandbox Code Playgroud)
Bit Mask(0xFFFFFFFF
)值取决于Int的大小,因为Int大小取决于机器.
如果值超出整数范围,以下解决方案将截断为 int.MinValue/int.MaxValue。
myLong < int.MinValue ? int.MinValue : (myLong > int.MaxValue ? int.MaxValue : (int)myLong)
Run Code Online (Sandbox Code Playgroud)