1

I've been suggested a TCP-like checksum, which consists of the sum of the (integer) sequence and ack field values, added to a character-by-character sum of the payload field of the packet (i.e., treat each character as if it were an 8 bit integer and just add them together).

I'm assuming it would go along the lines of:

char[] a = data.toCharArray();
for (int i = 0; int < len; i++) {
   ...
}

Though I'm pretty clueless as to how I could complete the actual conversion?

My data is string, and I wish to go through the string (converted to a char array (though if there's a better way to do this let me know!)) and now I'm ready to iterate though how does one convert each character to an int. I will then be summing the total.

2
  • simple: in your for loop: int val = a[i]; Commented Mar 27, 2019 at 14:56
  • and this converts the current character in the loop? Commented Mar 27, 2019 at 14:57

1 Answer 1

3

As String contains Unicode, and char is a two-byte UTF-16 implementation of Unicode, it might be better to first convert the String to bytes:

byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
data = new String(bytes, StandardCharsets.UTF_8); // Inverse.

int crc = 0;
for (byte b : bytes) {
    int n = b & 0xFF; // An int 0 .. 255 without sign extension
    crc ^= n;
}

Now you can handle any Unicode content of a String. UTF-8 is optimal when sufficient ASCII letters are used, like Chinese HTML pages. (For a Chinese plain text UTF-16 might be better.)

Sign up to request clarification or add additional context in comments.

4 Comments

How would I now go from [B@106d69c to an integer?
byte is a signed 8 bit integer, hence you are almost there. I added an example for loop. The toString of a byte array is just its type code [B (array of byte) and object address/handle @106d69c
The above loop provides me with an outcome of 0, I don't understand why you would use the XOR operand?
That was just an example, the calculation I leave as your effort (+=, and that ack field). So not to suggest having a result; info fails.

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.