2

I have to convert this little piece of C# code to Java:

const int AM = 65521;
int GetCCSufix(string a)
{            
    int c = 1, b = 0, d, e;
    var chars = a.ToCharArray();
    for(e =0; e< chars.Length; e ++)
    {
        d = chars[e];
        c = (c + d) % AM;
        b = (b + c) % AM;
    }
    return b << 16 | c;
}

And I made it this:

private int getSuffix(String a) {
    int constant = 65521;
    int c = 1;
    int b = 0;
    int d = 0;
    int e = 0;
    for(e = 0; e < a.length(); e++){
        d = a.charAt(e);
        c = (c + d) % constant;
        b = (b + c) % constant;
    }
    return b << 16 | c;
}

However, this doesn't seem to give me the same output as the C# code. What am i doing wrong?

6
  • 1
    Could you put a break point on return statement and check if the value of b is same for both codes (for same string) ? Commented Feb 25, 2014 at 16:56
  • 1
    here the variable d must be char array after that you can covert it using Integer.parseInt(); the charAt() method will return char array only. Commented Feb 25, 2014 at 17:00
  • @Sathesh: charAt returns a char not a string array... docs.oracle.com/javase/6/docs/api/java/lang/… Commented Feb 25, 2014 at 17:03
  • 1
    How does the output differ? Provide some sample input/output for both programs to demonstrate how it's not working, rather than just saying that it's not working. Commented Feb 25, 2014 at 17:08
  • 1
    I am very sorry, the code I posted is actually working. I just discovered that i was giving it the wrong input a. Sorry for the inconvenience. Commented Feb 25, 2014 at 17:10

1 Answer 1

5

I did a verbatim translation of the original code, see if this gives the correct result. What values are you using for testing, that give different results?

private static final int AM = 65521;

int getCCSuffix(String a) {
    int c = 1, b = 0, d = 0, e;
    char[] chars = a.toCharArray();
    for (e = 0; e < chars.length; e++) {
        d = chars[e];
        c = (c + d) % AM;
        b = (b + c) % AM;
    }
    return b << 16 | c;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am very sorry, the code I posted is actually working. I just discovered that i was giving it the wrong input a. Sorry for the inconvenience. Thanks for your work anyway! Your code is correct as well.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.