I have a javascript function that has functionality that I would like to convert to C#. I'm not sure how to properly translate this.
Can anyone help?
function validateSequenceNumber(val, num) {
var seqNumber = ((parseFloat(num) + 0xCED9) * 0x8088405) & 0xFFFF
var checksum = seqNumber.toString(16).toUpperC开发者_JAVA百科ase()
if (checksum != val.substring(11, 15)) {
return false;
}
return true;
}
parseFloat
becomes float.Parse
, seqNumber.toString(16)
becomes string.Format("{0:x}", seqNumber).ToUpper();
And note on substring parameters in C# are not start, end; rather start, length. So be careful. function
becomes bool
obviously. And I think that's it.
The string functions used should also use the invariant culture, since the function doesn't appear to be used for text display. Below is how the function might be converted:
private static bool ValidateSequenceNumber(string val, string num) {
System.Globalization.CultureInfo inv=System.Globalization.CultureInfo.InvariantCulture;
int seqNumber = unchecked((((int)Double.Parse(num,System.Globalization.NumberStyles.Any,inv) + 0xCED9) * 0x8088405) & 0xFFFF);
string checksum = seqNumber.ToString("X",inv).ToUpperInvariant();
if (checksum != val.Substring(11, 4)) {
return false;
}
return true;
}
EDIT: Added Unchecked keyword: the overflow errors that would occur appear to be unimportant here.
public bool validateSequenceNumber(string val, int num)
{
float seqNumber = (Int32)((Single.Parse(num) + 0xCED9) * 0x8088405) & 0xFFFF;
string checksum = seqNumber.ToString("X").ToUpper();
return (checksum != val.Substring(11, 4) ? false : true);
}
精彩评论