我可以将 long 转换为 int 吗?
我想将 long
转换为 int
。
如果long
的值> > int.MaxValue
,我很高兴让它环绕起来。
什么是最好的方法?
I want to convert long
to int
.
If the value of long
> int.MaxValue
, I am happy to let it wrap around.
What is the best way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
只需执行
(int)myLongValue
即可。 它会在unchecked
上下文(这是编译器默认值)中完全执行您想要的操作(丢弃 MSB 并获取 LSB)。 如果该值不适合int
,它将在checked
上下文中抛出OverflowException
:Just do
(int)myLongValue
. It'll do exactly what you want (discarding MSBs and taking LSBs) inunchecked
context (which is the compiler default). It'll throwOverflowException
inchecked
context if the value doesn't fit in anint
:虽然我不知道当它大于 int.MaxValue 时它会做什么。
Though I don't know what it will do when it's greater than int.MaxValue.
有时您实际上并不对实际值感兴趣,而是对它作为校验和/哈希码的用法感兴趣。 在这种情况下,内置方法
GetHashCode()
是一个不错的选择: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:安全且最快的方法是在转换之前使用位掩码...
位掩码(
0xFFFFFFFF
)值将取决于 Int 的大小,因为 Int 大小取决于机器。The safe and fastest way is to use Bit Masking before cast...
The Bit Mask (
0xFFFFFFFF
) value will depend on the size of Int because Int size is dependent on machine.一种可能的方法是使用模运算符仅让值保持在 int32 范围内,然后将其转换为 int。
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.
如果值超出整数范围,以下解决方案将截断为 int.MinValue/int.MaxValue。
The following solution will truncate to int.MinValue/int.MaxValue if the value is out of Integer bounds.
从数学角度来说,这不是
正确的方法吗?
Wouldn't
be the correct way, mathematically speaking?
它可以通过转换
但如果值超出 Int32 类型的范围,则会抛出 OverflowException。
基本测试将向我们展示它是如何工作的:
这里有一个更长的解释。
It can convert by
But it will throw an OverflowException if it the value is outside range of the Int32 Type.
A basic test will show us how it works:
Here there is a longer explanation.