开发者

Converting JavaScript to C#

I'm a bit baffled when it comes to converting this javascript over to C#...

Any help would be appreciated!

Here is the javascript:

function d(strInput) {
    strInput = decoder(strInput);
    var strOutput开发者_开发技巧 = "";
    var intOffset = (key + 112) / 12;
    for (i = 4; i < strInput.length; i++) {
        thisCharCode = strInput.charCodeAt(i);
        newCharCode = thisCharCode - intOffset;
        strOutput += String.fromCharCode(newCharCode)
    }
    document.write(strOutput)
}

And this is my attempt at converting it to C#. It works some of the time, but most of the time for negative numbers as the key...

public string decode(int key, string data)
{
    int i;
    string strInput = base64Decode(data);
    StringBuilder strOutput = new StringBuilder("");

    int intOffset = (key + 112) / 12;
    for (i = 4; i < strInput.Length; i++)
    {

        int thisCharCode = strInput[i];
        char newCharCode = (char)(thisCharCode - intOffset);
        strOutput.Append(newCharCode);
    }
    return strOutput.ToString();
}

Currently it outputs the following:

(int key = 212, string data = "U0lra36DfImFkImOkImCW4OKj4h8hIdJfoqI")
Output = {c¬a¬¬¬¬¬¬¬¬@¬¬¬¬a¬¬.c¬¬}


(int key = -88, string data = "T1RXYmV0cHFkZ3R1MzQ1Ng==")
Output = {crnobers1234}


This code gives the same results as your example, for the two sample inputs:

    public string decoder(string data)
    {
        string b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        char o1, o2, o3;
        int h1, h2, h3, h4, bits, i = 0;
        string enc = "";
        do
        {
            h1 = b64.IndexOf(data.Substring(i++, 1));
            h2 = b64.IndexOf(data.Substring(i++, 1));
            h3 = b64.IndexOf(data.Substring(i++, 1));
            h4 = b64.IndexOf(data.Substring(i++, 1));
            bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
            o1 = (char)(bits >> 16 & 0xff);
            o2 = (char)(bits >> 8 & 0xff);
            o3 = (char)(bits & 0xff);
            if (h3 == 64) enc += new string(new char[] { o1 });
            else if (h4 == 64) enc += new string(new char[] { o1, o2 });
            else enc += new string(new char[] { o1, o2, o3 });
        } while (i < data.Length);
        return enc;
    }

    public string d(int key, string data)
    {
        int i;
        string strInput = decoder(data);
        StringBuilder strOutput = new StringBuilder("");

        int intOffset = (key + 112) / 12;
        for (i = 4; i < strInput.Length; i++)
        {

            int thisCharCode = strInput[i];
            char newCharCode = (char)(thisCharCode - intOffset);
            strOutput.Append(newCharCode);
        }
        return strOutput.ToString();
    }

I'm sure it could do with some cleaning up! It's just a verbatim translation of your Javascript decoder() function that did it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜