Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET code returning different result than C# code

The following code in C# gives result "228452386"

UInt32 a;

int k = 0;

a = 0x9E3779B9;

a += (UInt32)(url[k + 0] + (url[k + 1] << 8) + (url[k + 2] << 16) + (url[k + 3] << 24));

After above code is ran, "a" contains "228452386".

But the following same code in VB.NET results in "Arithmetic operation resulted in an overflow". Basically the last statement is returning value "1868983913", so the runtime error is generated.

Dim a As UInt32

Dim k As Integer = 0

a = &H9E3779B9UI

a += CUInt(AscW(url(k + 0)) + (AscW(url(k + 1)) << 8) + (AscW(url(k + 2)) << 16) + (AscW(url(k + 3)) << 24))

Please note the variable "url" in the above code could be any string and it is same for both codes.

When I run the following statements in both C# and VB.NET than they both return same value

C#

(UInt32)(url[k + 0] + (url[k + 1] << 8) + (url[k + 2] << 16) + (url[k + 3] << 24))

VB.NET

CUInt(AscW(url(k + 0)) + (AscW(url(k + 1)) << 8) + (AscW(url(k + 2)) << 16) + (AscW(url(k + 3)) << 24))

Both statements return the value "1868983913" for "url" "info:microsoft.com". But when I run the complete statement with a += ......... then VB.NET gives an error while C# returns the value "228452386".

like image 404
Ali Avatar asked Dec 13 '25 16:12

Ali


1 Answers

You have an overflow, because the result of adding the two numbers you're adding are larger than what fits in an UInt.

The resulting number is a 33 bit number, UInts fit only 32 bits.

  • In C#, the most significant bit is just chopped of, keeping the 32 bits that fit inside the UInt. (This new value is not the actual result of adding your numbers.)
  • In VB.NET you get an exception stating that the number doesn't fit.

The VB.NET compiler (or VS) allows you to turn of this overflow checking, so that VB.NET will behave like C# in this case.

like image 179
Arjan Einbu Avatar answered Dec 15 '25 06:12

Arjan Einbu