开发者

Why does assigning 0xFFFFFFFF to a UInteger generate an error in VB.NET?

开发者 https://www.devze.com 2023-01-14 23:30 出处:网络
A UInteger data type holds any value between 0 and 4,294,967,295 (ref. MSDN). If I try this code in VB开发者_如何学Go.NET, I get a compiler error:

A UInteger data type holds any value between 0 and 4,294,967,295 (ref. MSDN).

If I try this code in VB开发者_如何学Go.NET, I get a compiler error:

Dim Test As UInteger = &HFFFFFFFF

Error: "Constant expression not representable in type 'UInteger'.

Why I can't set 0xFFFFFFFF (4,294,967,295) to a UInteger if this type can hold this value?


I believe it's because the literal &HFFFFFFFF is interpreted by the VB.NET compiler as an Integer, and that value for an Integer is a negative number (-1), which obviously can't be cast to a UInteger.

This issue is easily fixed by writing &HFFFFFFFFUI, appending the UI suffix to treat the literal as a UInteger.


You could use the MaxValue constant:

Dim Test As UInteger = UInteger.MaxValue


Looking at this article, it appears the solution is to set the value as &HFFFFFFFFUI, since according the article:

If you just write &HFFFFFFFF then it is treated as a signed 32 bit integer, value is -1, and you can't assign that to a UInteger.

If you write &HFFFFFFFFL then it is treated as a signed 64 bit integer, now the binary is: 0000000000000000000000000000000011111111111111111111111111111111


Incidentally, it's worth nothing that "LongValue = LongValue And Not &h8000" just clears one bit in 'LongValue', as does "LongValue = LongValue And Not &h800000000000". On the other hand, "LongValue = LongValue And Not &h80000000" will clear out the top 33 bits of LongValue.


You can write "-1" which is the same as 4,294,967,295

0

精彩评论

暂无评论...
验证码 换一张
取 消