6

In C#:

0x80000000==2147483648 //outputs True

In VB.NET:

&H80000000=2147483648 'outputs False

How is this possible?

user3666697
  • 303
  • 1
  • 3
  • 16

3 Answers3

10

This is related to the history behind the languages.

C# always supported unsigned integers. The value you use are too large for int so the compiler picks the next type that can correctly represent the value. Which is uint for both.

VB.NET didn't acquire unsigned integer support until version 8 (.NET 2.0). So traditionally, the compiler was forced to pick Long as the type for the 2147483648 literal. The rule was however different for the hexadecimal literal, it traditionally supported specifying the bit pattern of a negative value (see section 2.4.2 in the language spec). So &H80000000 is a literal of type Integer with the value -2147483648 and 2147483648 is a Long. Thus the mismatch.

If you think VB.NET is a quirky language then I'd invite you to read this post :)

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
6

The VB version should be:

&H80000000L=2147483648

Without the 'long' specifier ('L'), VB will try to interpret &H8000000 as an integer. If you force it to consider this as a long type, then you'll get the same result. &H80000000UI will also work - actually this is the type (UInt32) that C# regards the literal as.

Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28
1

This happens because the type of the hexadecimal number is UInt32 in C# and Int32 in VB.NET.
The binary representation of the hexadecimal number is:

10000000000000000000000000000000

Both UInt32 and Int32 take 32 bits, but because Int32 is signed, the first bit is considered a sign to indicate whether the number is negative or not: 0 for positive, 1 for negative. To convert a negative binary number to decimal, do this:

  1. Invert the bits. You get 01111111111111111111111111111111.
  2. Convert this to decimal. You get 2147483647.
  3. Add 1 to this number. You get 2147483648.
  4. Make this negative. You get -2147483648, which is equal to &H80000000 in VB.NET.
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51