I try to reach your idea because of so many redundancy codes. By using:
SubString
exports each character even Encoding.ASCII.GetBytes
can return all byte array from these characters
BitConverter
expected of 4-byte binary input as well
https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter.toint32 and seem this function is no help at all
- Declare iLoop = 1 but inside loop does iLoop - 1
sPassConv
gets value from iTotal so many times, should put outside the loop
Quick fix from your code:
public static string PassConv(string Password)
{
int iLoop;
int iL;
int iTotal;
int iValue;
string sPassConv = "";
iL = 3;
iTotal = 0;
for (iLoop = 1; iLoop <= Password.Length; iLoop++)
{
string sNo = Password.Substring(iLoop - 1, 1);
iValue = Encoding.ASCII.GetBytes(sNo)[0];
iTotal = iTotal + iValue * (iL + iLoop - 1);
sPassConv = iTotal.ToString();
}
return sPassConv;
}
A little bit refactor
public static string PassConv2(string Password, int iL = 3)
{
int iTotal = 0;
var bytes = Encoding.ASCII.GetBytes(Password);
for (var iLoop = 0; iLoop < bytes.Length; iLoop++)
{
// bytes[iLoop] = iValue
iTotal += bytes[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
This function is need to be improved because it does loop 2 times, first to bytes and second to calculate. Since every character can convert to ASCII
even Extended ASCII
, so we could cast it directly. PassConv3
gives more exact when input is Unicode such as "Áaa", the Encoding.ASCII.GetByteswill
cast as "?aa" with '?' represents 63 ASCII
public static string PassConv3(string Password, int iL = 3)
{
int iTotal = 0;
for (var iLoop = 0; iLoop < Password.Length; iLoop++)
{
iTotal += Password[iLoop] * (iL + iLoop);
}
return iTotal.ToString();
}
And the result
public static void MainFunc()
{
Console.WriteLine(PassConv("ABCD")); // 1202
Console.WriteLine(PassConv2("ABCD")); // 1202
Console.WriteLine(PassConv3("ABCD")); // 1202
}
Hope it helps !