1

I need the following function converted to VB.NET, but I'm not sure how to handle the statement

res = (uint)((h * 0x21) + c);

Complete function:

private static uint convert(string input)
{
    uint res = 0;
    foreach (int c in input)
        res = (uint)((res * 0x21) + c);
    return res;
}

I created the following, but I get an overflow error:

Private Shared Function convert(ByVal input As String) As UInteger

    Dim res As UInteger = 0
    For Each c In input
        res = CUInt((res * &H21) + Asc(c)) ' also tried AscW 
    Next
    Return res

End Function

What am I missing? Can someone explain the details?

durron597
  • 31,968
  • 17
  • 99
  • 158
Anax
  • 9,122
  • 5
  • 34
  • 68

2 Answers2

3

Your code is correct. The calculation is overflowing after just a few characters since res increases exponentially with each iteration (and it’s not the conversion on the character that’s causing the overflow, it’s the unsigned integer that overflows).

C# by default allows integer operations to overflow – VB doesn’t. You can disable the overflow check in the project settings of VB, though. However I would try not to rely on this. Is there a reason this particular C# has to be ported? After all, you can effortlessly mix C# and VB libraries.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

Here is a useful online converter: http://www.developerfusion.com/tools/convert/csharp-to-vb/

Eric Dahlvang
  • 8,252
  • 4
  • 29
  • 50
  • It *should* return the character code. That’s what the C# code does, too, only implicitly. Your code, on the other hand, won’t compile. – Konrad Rudolph Jul 18 '12 at 11:35