There is a C application that takes a string input and returns a short (0-65535) value using a CRC algorithm. I need to get the same output from a JAVA method such that the input and the output from the Java method remains the same as the C code since parts of the application cannot change. I tried google and other posts, but haven't found a solution.
I tried google and other posts, but haven't found a solution.
It is basically a single loop with two expressions. Besides being careful with the calculations to make sure that you don't accidently do a signed operation (as the C variables are unsigned)... How hard is it to port it?
(c = *pName++) != 0 reads the next character of the char*, and checks if it isn't 0 (actually '\0', the NULL character).
Now, if you replace char* with String, then the following is how you usually iterate over a String:
Since char is actually numeric you can use it in your calculations without any problems.
Just for reference, you can also use a CharacterIterator:
The former method is preferred though.
And as I already hinted, you really have to be careful to not do a signed operation. Keep in mind that the original C program used unsigned variables, and you are now using signed variables, which behaves differently under certain conditions.
The one that you seem to be running into is the assignment. For example, assigning a byte to an int may not be what you want in all cases...
int i = b;
If the sign bit (high bit) of the byte b is set, it will sign extend to the int -- this is not what you want. You need to be careful to remove any sign extended created bits when you do this...