VB.NET code returns a different result than C # code

The following code in C # gives the 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 executing the above code, "a" contains "228452386".

But the following code in VB.NET causes the "Arithmetic operation to lead to overflow." Basically, the last statement returns the value "1868983913", so a 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))

Note that the url variable in the above code can be any string, and it is the same for both codes.

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

WITH#

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

"1868983913" "url" "info: microsoft.com". a + =........., VB.NET , # "228452386" .

+3
3

, , , UInt.

- 33- , UInts - 32 .

  • # , 32 , UInt. ( .)
  • VB.NET , , .

VB.NET( VS) , VB.NET # .

+2

VB.NET , # - . #:

UInt32 a;
int k = 0;
a = 0x9E3779B9;
checked{
    a += (UInt32)(url[k + 0] + (url[k + 1] << 8) + (url[k + 2] << 16) + (url[k + 3] << 24));
}

: .

+1

Use the following VB.NET code:

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

AscW returns an integer (signed), and what you need is unsigned.

EDIT

It works:

    Dim a As Int64
    Dim result As UInt32

    Dim k As Integer = 0

    Dim url As String = "info:microsoft.com"

    a = &H9E3779B9UI

    Dim a1 As UInt32 = 0
    Dim a2 As UInt32 = 0
    Dim a3 As UInt32 = 0
    Dim a4 As UInt32 = 0

    a1 = AscW(url(k + 0))
    a2 = AscW(url(k + 1)) << 8
    a3 = AscW(url(k + 2)) << 16
    a4 = AscW(url(k + 3)) << 24

    a = (a + a1 + a2 + a3 + a4) And &HFFFFFFF
    result = Convert.ToUInt32(a)
0
source

All Articles