• Converting a C# function to Visual Basic.NET
    7 replies, posted
Hi, Could someone please help me with this conversion. I've tried to convert it my own self, and with a program, but it seems to not work. The code comes from:[url]http://stackoverflow.com/questions/548158/fixed-length-numeric-hash-code-from-variable-length-string-in-c-sharp[/url] [code]const int MUST_BE_LESS_THAN = 100000000; // 8 decimal digits public int GetStableHash(string s) { uint hash = 0; // if you care this can be done much faster with unsafe // using fixed char* reinterpreted as a byte* foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s)) { hash += b; hash += (hash << 10); hash ^= (hash >> 6); } // final avalanche hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); // helpfully we only want positive integer < MUST_BE_LESS_THAN // so simple truncate cast is ok if not perfect return (int)(hash % MUST_BE_LESS_THAN) }[/code] Here is my version of it in VB.NET [code] Const MUST_BE_LESS_THAN As Integer = 100000000 Function GetStableHash(ByVal s As String) As Integer Dim hash As UInteger = 0 For Each b In System.Text.Encoding.Unicode.GetBytes(s) hash += b hash += (hash << 10) hash = hash Xor (hash >> 6) Next hash += (hash << 3) hash = hash Xor (hash >> 11) hash += (hash << 15) Return Int(hash Mod MUST_BE_LESS_THAN) End Function[/code] It seems to be the same code, but only Visual Basic results an error. There is an overflow at "hash += (hash << 10)". Thank you! Artem
Hmm, looks the same. The only thing different, that I could find, is the for each loop. Shouldn't it be "For Each b as Byte in System.Text.Encoding.Unicode.GetBytes(s)"? Edit: Are you sure this works in C#?
I've changed it to Byte, but the result seems to be the same.. :( Yes, this code works in c#.
If your expected output for "apples" is 52069482 then you are just going to have to disable your overflow checks in the project properties. The type UInteger ( uint32 ) has a maximum value of 4294967295 and the function is going to quickly overflow it. Go to project properties, select the compile tab, click Advanced Compile Options at the bottom, and check "Remove integer overflow checks"
[url]http://www.developerfusion.com/tools/convert/csharp-to-vb/[/url] This helps me all most every time I have to do VB work.
Thank you for great tips! //Artem
[QUOTE=artemlos;35177086]Thank you for great tips! //Artem[/QUOTE] You don't have to sign your posts you know, your name is displayed next to your post.
Why not compile it to a managed dll and use it in whichever .NET application you please?
Sorry, you need to Log In to post a reply to this thread.