PDA

View Full Version : PRNG in C#, VB, result is different, can someone help me?



BarkingFrog
May 31st, 2009, 12:54 AM
I'm only using this for personal use, just to calculate things..
but I need some help.. I use VisualStudio 2005

first, i used VB


Private Function PRNG(ByVal seed As String) As String
Dim temp As String = ""
Dim t As UInt64
t = Convert.ToUInt64("0x41C64E6D", 16) * Convert.ToUInt64(seed, 16) + Convert.ToUInt64("0x6073", 16)
temp = Hex(t)
If temp.Length < 16 Then
For t = 0 To 15 - temp.Length Step 1 'just to add zero
temp = "0" & temp
Next
End If
PRNG = temp
End Function


then for some reason i have to convert it to C#, here is the code:


using Microsoft.VisualBasic; //for Conversion

private const UInt64 factor = 0x41C64E6D;
private const UInt64 adder = 0x6073;

//...

private string generate(String seed) {
return temp = Conversion.Hex( (factor * Convert.ToUInt64(seed, 16) + adder));
}



but i get different result, well the LSB is the same, but the MSB is different.. any clue? :bidoof::bidoof::bidoof:

thx a lot

codemonkey85
May 31st, 2009, 02:03 AM
I am not sure why the result would be different, but here's what the VB.Net code converted to C# looks like for me (courtesy of this page (http://www.developerfusion.com/tools/convert/vb-to-csharp/).):


private string PRNG(string seed)
{
string temp = "";
UInt64 t = default(UInt64);
t = Convert.ToUInt64("0x41C64E6D", 16) * Convert.ToUInt64(seed, 16) + Convert.ToUInt64("0x6073", 16);
temp = Conversion.Hex(t);
if (temp.Length < 16) {
for (t = 0; t <= 15 - temp.Length; t += 1) {
//just to add zero
temp = "0" + temp;
}
}
return temp;
}

mingot
May 31st, 2009, 05:28 PM
public UInt32 GetNext32BitNumber()
{
seed = seed * 0x41C64E6D + 0x6073;

return seed;
}

No need for all that 64 bit stuff.

damio
Jun 1st, 2009, 02:42 AM
public UInt32 GetNext32BitNumber()
{
seed = seed * 0x41C64E6D + 0x6073;

return seed;
}

No need for all that 64 bit stuff.

Shouldn't it be seed = (seed * 0x41C64E6D + 0x6073) & 0xFFFFFFFF;
?

mingot
Jun 1st, 2009, 02:09 PM
Nope. The return will be uint anyhow.

BarkingFrog
Jun 4th, 2009, 10:01 AM
Thanks for all of the help, I'll try that again..
oh, for the UInt64, i've tried UInt32, sometimes it says overflow.. so I decided to use UInt64.. but I think Mingot is correct, I'll try again..

@Damio
the modulo thing is somehow does not effect the result..

well I think it's because the conversion, somehow the result from C# is like rounded up..

thanks all..