C# 中常量值计算错误溢出
我需要分配整数(或其他数据类型)的常量值。
我在作业中遇到“无法转换...”错误。
投射似乎无法处理“溢出...”错误。
这有什么问题吗?
I need to assign constant value in integer (or other data type).
I got "Cannot convert ..." error with the assignment.
Casting doesn't seem to work with "Overflow ..." error.
What's wrong with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在常量中定义了太多
F
。使用0xFFFFFFFF
,编译器必须选择一个支持0xFFFFFFFF
正值的存储位置。Int32
的最大正值是0x7FFFFFFF
,因此编译器会正确地出错。唯一可以保存0xFFFFFFFF
的类型是uint
或 64 位存储之一。要解决此问题,只需使用
Int32.MaxValue
You've defined too many
F
s in the constant. Using0xFFFFFFFF
the compiler must choose a a storage location that supports a positive value of0xFFFFFFFF
. The max positive value of anInt32
is instead0x7FFFFFFF
and hence the compiler correctly errors. The only types which can hold0xFFFFFFFF
areuint
or one of the 64 bit storages.To fix this just use
Int32.MaxValue
32 位 int 可以表示的最大(最大正数)数字是 0x7fffffff。前面出现 7 而不是另一个 f 是因为 int 有符号,所以最高位代表数字的符号(正或负)。
在第一个示例中,编译器看到一个只能由 unsigned int 表示的数字,因此它假设它是 UInt32。这无法转换为 int,因此会出现错误。
在第二个示例中,您使用强制转换来强制转换,但数字不适合 int,因此会发生溢出(数字太大)。
为了避免溢出,选项包括:
未检查的 {}
块中分配 0xffffffff,以便写入原始二进制值而不检查溢出。这将读回 -1。The maximum (largest positive) number a 32 bit int can represent is 0x7fffffff. The 7 at the front occurs rather than another f is because int is signed, so the top bit represents the sign (positive or negative) of the number.
In your first example the compiler sees a number that can only be represented by an unsigned int, so it assumes it is a UInt32. This cannot be converted to an int, hence the error.
In your second example you are forcing the conversion with a cast, but the number won't fit into an int, so an overflow (number too big) occurs.
To avoid an overflow, options include:
unchecked {}
block so the raw binary value is written without checking for an overflow. This will read back as -1.