VB.NET 中无符号左移?
这对人们来说应该是一件容易的事,但是如何在 VB.NET 中实现无符号左移 使用Option Strict
时?
也许我做错了,但是在尝试实现我自己的 IP2Long 函数时(我有我的理由),我正在测试一些东西以确保我的头脑正确地围绕转换过程。我尝试了一些测试,所有似乎都会导致错误。
Dim a As Int32
a = CUint(172 << 24) 'Constant expression not representable in type 'UInteger'
a = DirectCast((172 << 24), UInt32) 'Value of type 'Integer' cannot be converted to 'UInteger'
a = Convert.ToUInt32(172 << 24) 'Compiles, but throws an OverflowException
最后一个尤其令人困惑。 <代码> 172 << 24 只是 2,885,681,152,远低于 UInt32 数据类型所施加的限制。我的假设是.NET 在有符号模式下进行左移,然后尝试转换为无符号,这会引发某种错误。
基本上,我的问题可以归结为:为什么无符号数字有时必须像对 .NET 框架的黑客攻击一样?对于 Microsoft 来说,将无符号数据类型内置到框架中真的那么困难吗?
This should be an easy one for folks, but how do I pull off an unsigned left shift in VB.NET while using Option Strict
?
Maybe I am doing it wrong, but while trying to implement my own IP2Long function (I have my reasons), I'm testing things to make sure I have my head wrapped around the conversion process properly. I tried a few tests, and all seem to cause errors.
Dim a As Int32
a = CUint(172 << 24) 'Constant expression not representable in type 'UInteger'
a = DirectCast((172 << 24), UInt32) 'Value of type 'Integer' cannot be converted to 'UInteger'
a = Convert.ToUInt32(172 << 24) 'Compiles, but throws an OverflowException
The last one is especially befuddling. 172 << 24
is a mere 2,885,681,152, well under the limit imposed by the UInt32 data type. My assumption is .NET is doing the left-shift in signed mode, then tries to convert, to unsigned, and this tosses up some kind of error.
Basically, my question boils down to this: why do unsigned numerics have to act like such hacks to the .NET framework at times? Is it really that hard for Microsoft to make unsigned data types intrinsic to the framework?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个错误并没有错。 172占用8位。将其移位 24 位,第 8 位现在是第 32 位。这是保留的符号位。因此,它在技术上是溢出的。
像 C# 一样对待整数
VB.NET 将检查整数溢出,这与 C# 不同。
要让VB.NET忽略OveflowExceptions异常,请转到:
或使用
显式状态位操作
进行编译如果您决定在代码中保留溢出检查,则必须使用显式告诉它您正在使用位操作BitConverter 类:
Visual Basic 文字
另外请记住,您可以添加文字到您的 VB 代码中。 NET 并明确声明常量为无符号。
This error is not wrong. 172 takes up 8 bits. You shift it 24 bits and the 8th bit is now the 32nd bit. This is a reserved sign bit. Therefore it is technically overflowing.
Treat integers like C#
VB.NET will check for an integer overflow unlike in C#.
To get VB.NET to ignore OveflowExceptions Exceptions goto:
Or compile with
Explicit state bit operations
If you are determined to leave overflow checks in your code, you have to explicitly tell it you are using bit operations using the BitConverter Class:
Visual Basic literals
Also keep in mind you can add literals to your code in VB.NET and explicitly state constants as unsigned.