我想将long
转换为int
。
如果long
的值 > int.MaxValue
, 我希望它可以循环回来。
最好的方式是什么?
我想将long
转换为int
。
如果long
的值 > int.MaxValue
, 我希望它可以循环回来。
最好的方式是什么?
只需执行(int)myLongValue
即可。在unchecked
上下文中(这是编译器默认设置),它将完全按照您的要求执行(丢弃MSB并获取LSB)。如果该值不适合int
,则在checked
上下文中会抛出OverflowException
异常:
int myIntValue = unchecked((int)myLongValue);
Convert.ToInt32(myValue);
虽然我不知道当它大于int.MaxValue时会发生什么。
Convert
不好。 - ruffinif (value > Int32.MaxValue)
return Int32.MaxValue;
else
return Convert.ToInt32( value );
- Sergeyreturn value < Int32.MinValue ? Int32.MinValue : (value > Int32.MaxValue ? Int32.MaxValue : (int)value);
- ToolmakerSteveGetHashCode()
是一个不错的选择:int checkSumAsInt32 = checkSumAsIn64.GetHashCode();
GetHashCode
是一个合适的选择。如果您想要一个持久的校验和 - 一个在以后运行应用程序时将保持相同的值,则不要使用 GetHashCode
,因为它不能保证永远使用相同的算法。 - ToolmakerSteve最安全和最快的方法是在强制类型转换之前使用位掩码...
int MyInt = (int) ( MyLong & 0xFFFFFFFF )
位掩码(0xFFFFFFFF
)的值取决于Int的大小,因为Int的大小取决于机器。
一种可能的方法是使用模运算符仅让值保留在int32范围内,然后将其转换为int。
var intValue= (int)(longValue % Int32.MaxValue);
(int)(longValue > Int32.MaxValue ? (longValue % Int32.MaxValue) + 1 : longValue)
。类似的逻辑也可以用于负值:(int)(longValue < Int32.MinValue ? (longValue % Int32.MaxValue) - 1 ? (longValue > Int32.MaxValue ? (longValue % Int32.MaxValue) + 1 : longValue))
。 - ToolmakerStevemyLong < int.MinValue ? int.MinValue : (myLong > int.MaxValue ? int.MaxValue : (int)myLong)
long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
int result;
foreach (long number in numbers)
{
try {
result = Convert.ToInt32(number);
Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
number.GetType().Name, number,
result.GetType().Name, result);
}
catch (OverflowException) {
Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.",
number.GetType().Name, number);
}
}
// The example displays the following output:
// The Int64 value -9223372036854775808 is outside the range of the Int32 type.
// Converted the Int64 value -1 to the Int32 value -1.
// Converted the Int64 value 0 to the Int32 value 0.
// Converted the Int64 value 121 to the Int32 value 121.
// Converted the Int64 value 340 to the Int32 value 340.
// The Int64 value 9223372036854775807 is outside the range of the Int32 type.
这里有更详细的解释。
Wouldn't
(int) Math.Min(Int32.MaxValue, longValue)
longValue
夹紧到最接近的可表示 int
。但它缺乏对于过于负面的输入的相同处理,这将导致最高有效位丢失;您还需要与 Int32.MinValue
进行比较。然而,原帖似乎并不想要夹紧。 - Jeppe Stig Nielsen(int)Math.Max(Int32.MinValue, Math.Min(Int32.MaxValue, longValue))
。然而,我发现等效的 https://dev59.com/CXRA5IYBdhLWcg3wsgPq#58011064 更容易理解。 - ToolmakerSteve
myLongValue
为正数时(4294967294 => -2
),myIntValue
可能会变成负数,反之亦然(-4294967296 => 0
)。因此,在实现CompareTo
操作时,你不能将一个long
减去另一个强制转换为int
并返回;对于某些值,你的比较将产生错误的结果。 - T.J. Crowdernew Random()
在内部使用Environment.TickCount
,不需要手动使用时钟滴答进行种子初始化。 - Mehrdad Afshari