3

I have a Javascript method. I wrote on C# but it dosen't work.

Javascript Code

var __AM = 65521;
    function cc(a) {
        var c = 1, b = 0, d, e;
        for (e = 0; e < a.length; e++) {
            d = a.charCodeAt(e);
            c = (c + d) % __AM;
            b = (b + c) % __AM;
        }
        return b << 16 | c;
    }

My written C# Code

        private string CC(string a)
    {
        var __AM = 65521;
        int e;
        long d;
        long c = 1, b = 0;
        for (e = 0; e < a.Length; e++)
        {
            var p = Encoding.Unicode.GetBytes(a[e].ToString());
            d = Convert.ToInt32(p.First());
            c = (c + d) % __AM;
            b = (b + c) % __AM;
        }
        return b.ToString() + c.ToString();
    }

JS Test

cc("4JipHEz53sU1406413803");

Result: 1132332429

C# Test

CC("4JipHEz53sU1406413803");

Result: 172781421

How Can I get JS value in C#?

5
  • 1
    try byte[] p = Encoding.ASCII.GetBytes(a); outside the loop then just use d = p[e]. Commented Jul 26, 2014 at 23:05
  • 2
    b.ToString() + c.ToString() is certainly not equivalent to b << 16 | c Commented Jul 26, 2014 at 23:07
  • This is Adler-32 checksum algorithm. Perhaps theres a built-in implementation in C#? I don't know. Commented Jul 26, 2014 at 23:11
  • It's wrong. Beacuse when it was converted to byte. Just first value of array is available Commented Jul 26, 2014 at 23:11
  • There is no reason to conver it to a byte. A string is basically a char[]. Simply cast the char to an int and you'll have the char code. Commented Jul 26, 2014 at 23:12

1 Answer 1

2

This code works:

private string cc(string a)
{
    var __AM = 65521;
    int e;
    long d;
    long c = 1, b = 0;
    for (e = 0; e < a.Length; e++)
    {
        d = (int)a[e];
        c = (c + d) % __AM;
        b = (b + c) % __AM;
    }
    return (b << 16 | c).ToString();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Howover, JavaScript always handle strings in UNICODE format, I don't know much about C# but maybe strings are not handled the same way. This code will certainly work for any "a-z 0-9" strings, but how about special characters? It is something that deserves further testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.