Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

0x80000000 == 2147483648 in C# but not in VB.NET

Tags:

c#

.net

vb.net

hex

In C#:

0x80000000==2147483648 //outputs True

In VB.NET:

&H80000000=2147483648 'outputs False

How is this possible?

like image 710
user3666697 Avatar asked May 25 '14 17:05

user3666697


3 Answers

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 :)

like image 183
Hans Passant Avatar answered Nov 04 '22 00:11

Hans Passant


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.

like image 33
Dave Doknjas Avatar answered Nov 04 '22 02:11

Dave Doknjas


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.
like image 1
ProgramFOX Avatar answered Nov 04 '22 01:11

ProgramFOX