Unsigned left shift in VB.NET?

断了今生、忘了曾经 提交于 2020-01-21 09:12:27

问题


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?


回答1:


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.

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:

Project properties->Compile->Advanced Compiler Option->"Remove integer overflow checks"

Or compile with

vbc foo.vb /removeintchecks

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:

''//This will work
a = BitConverter.ToInt32(BitConverter.GetBytes(172 << 24), 0) 

Visual Basic literals

Also keep in mind you can add literals to your code in VB.NET and explicitly state constants as unsigned.



来源:https://stackoverflow.com/questions/4515102/unsigned-left-shift-in-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!