Represent all bits of hexadecimal number in VB

Viewed 83

In C# the following works:

UInt32 MyUInt32 = 0xFFFFFFFF;
UInt64 MyUInt64 = 0xFFFFFFFFFFFFFFFF;

But the equivalent VB generates error BC30439: Constant expression not representable in type 'ULong':

Dim MyUInt32 As UInt32 = &HFFFFFFFF ' Error BC30439
Dim MyUInt64 As UInt64 = &HFFFFFFFFFFFFFFFF ' Also fails

Changing the initialisation value to the largest value representable as a signed integer (i.e. Int32 or Int64) works:

Dim MyUInt32 As UInt32 = &H7FFFFFFF ' Works
Dim MyUInt64 As UInt64 = &H7FFFFFFFFFFFFFFF ' Also works

Is there any way to get that final (32nd or 64th) bit in VB?

2 Answers

The issue is with your literals. By default, integer literals are treated as signed. If you want something other than the default, then (as can happen in other languages) you can tell the compiler.

The correct way to do this is:

Dim MyUInt32 As UInt32 = &HFFFFFFFFUI
Dim MyUInt64 As UInt64 = &HFFFFFFFFFFFFFFFFUL

Note the "UI" and "UL" on the end of the constants: these tell the compiler that they should be treated as unsigned int and unsigned long, respectively.

It's more common to need to do this when you want a shorter-than-default constant, e.g. specifying that a constant is a Single or a Short instead of a Double or an Integer.

(You can argue, and I probably wouldn't disagree, that in this specific case, the compiler should recognize what you want to do and automatically change the literals to unsigned, just as it automatically treats the longer one as a Long instead of an Integer.)

Jimi seldom makes answers; I don't know why

Open up Project -> Properties -> Compile, click the Advanced Compile Option button and tick Remove integer overflow checks. -- You have the same setting as C# now (which has the same option, but inverted).

If they do post an answer, comment on and i'll delete this one/that one can be accepted

Related