[英]Legacy vbscript to c# equivilent
我已經在要轉換為asp.net(現階段為2.0)的經典asp站點中繼承了舊的哈希算法。
為了我的一生,我無法完全理解較舊的功能,無法用C#編寫匹配的代碼。 我敢肯定這確實很簡單,但是目前我看不到樹木的樹林。
這是帶字符串的原始經典asp代碼,對等效C#代碼的任何幫助將不勝感激:
Function PHash( pValue )
Dim dValue
Dim dAccumulator
Dim lTemp
Dim sValue
sValue = UCase(Trim("" & pValue))
dAccumulator = 0
For lTemp = 1 to Len(sValue)
dValue = Asc(Mid(sValue, lTemp, 1))
If (lTemp AND 1) = 1 Then
dAccumulator = Sin( dAccumulator + dValue )
Else
dAccumulator = Cos( dAccumulator + dValue )
End If
Next
dAccumulator = dAccumulator * CLng(10 ^ 9)
PHash = CLng(dAccumulator)
End Function
我真的希望您能參考一兩個參考,但這是我能想到的最好的參考
private static long PHash(String pValue)
{
double dAccumulator = 0;
byte[] asciiBytes = Encoding.ASCII.GetBytes(pValue.Trim().ToUpper());
for (int i = 0; i < asciiBytes.Length; i++)
{
if ((i & 1) == 1)
dAccumulator = Math.Cos(dAccumulator + (double)asciiBytes[i]);
else
dAccumulator = Math.Sin(dAccumulator + (double)asciiBytes[i]);
}
dAccumulator = dAccumulator * Math.Pow(10,9);
return (long)dAccumulator;
}
沒有理由進行直接翻譯,因為這涉及很多浪費。 我將所有字符串解析邏輯替換為對字節數組的轉換,然后使用for循環對其進行迭代。 我們使用&
運算符在VB中復制AND運算符。 Sin
和Cos
現在是Math
類的方法,可以通過鏈接Trim()
和ToUpper()
方法來修剪字符串並將其轉換為大寫。 .NET中沒有指數運算符,因此Math.Pow()
替代了它。 請注意,我們將所有內容保持為雙精度直到返回行,在該行中,我們將值返回為long
您可以使用此代碼。 請參閱會話工具: http : //www.developerfusion.com/tools/convert/vb-to-csharp/? batchId=dbded81a-54c9-4df5-aced-4db45773c842
public object PHash(pValue)
{
dynamic dValue = null;
dynamic dAccumulator = null;
dynamic lTemp = null;
dynamic sValue = null;
sValue = Strings.UCase(Strings.Trim("" + pValue));
dAccumulator = 0;
for (lTemp = 1; lTemp <= Strings.Len(sValue); lTemp++) {
dValue = Strings.Asc(Strings.Mid(sValue, lTemp, 1));
if ((lTemp & 1) == 1) {
dAccumulator = Sin(dAccumulator + dValue);
} else {
dAccumulator = Cos(dAccumulator + dValue);
}
}
dAccumulator = dAccumulator * Convert.ToInt64(Math.Pow(10, 9));
return Convert.ToInt64(dAccumulator);
}
翻譯可能是這樣的:
public long PHash (string pValue)
{
int dValue;
double dAccumulator;
int lTemp;
string sValue;
sValue = pValue.Trim().ToUpper();
dAccumulator = 0;
for (lTemp = 1; lTemp <= sValue.Length; lTemp ++)
{
dValue = (int)char.Parse(sValue.Substring(lTemp, 1));
if ((lTemp % 1) == 1)
{
dAccumulator = Math.Sin(dAccumulator + dValue);
}
else
{
dAccumulator = Math.Cos(dAccumulator + dValue);
}
}
dAccumulator = dAccumulator * (long)(10 ^ 9);
return (long)(dAccumulator);
}
所轉換的函數為:修剪:刪除字符串左側和右側的空格。 在C#中:Trim()。 UCase:將指定的字符串轉換為大寫。 在C#中:ToUpper()。 中:從字符串中返回指定數量的字符。 在C#中:Substring()。 Len:返回字符串中的字符數。 在C#中:長度。 CLng:是對long類型的簡單轉換。 升序:解析為從char到int的簡單轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.