Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checksum calculation in android/java

Tags:

java

android

I wrote a checksum calculation function in android/java. the function as follows

void CalculateCheckSum( byte[] bytes ){
     short CheckSum = 0, i = 0;
     for( i = 0; i < bytes.length; i++ ){
        CheckSum = (short) ((short)CheckSum + (short)bytes[i]);
     }

     Log.i("Checksum", Integer.toHexString(CheckSum));
}

input values for calculation of checksum are 0xEF, 0x01, 0xEF, 0x01, 0x33, 0x0C, 0xB8, 0xE5, 0xFC, 0x34, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF. I manually calculated the checksum value and result is 0xCE4. When using the above function i get answer as 0xFFFFFFE4. Is any error in my calculation, if yes then please correct me.

thanks

like image 436
Riskhan Avatar asked Sep 11 '12 07:09

Riskhan


3 Answers

The problem here is the (short) cast of bytes[i]. It extends the sign. You should change (short)bytes[i] to (bytes[i] & 0xff). This will give you the correct answer.

It has nothing to do with byte overflow, contrary to most of the other answers. You don't have to change the array type either.

like image 137
user207421 Avatar answered Sep 30 '22 08:09

user207421


Use a debugger and debug your code. Generally though, if you keep adding stuff up, even if you use an int or a long, it is bound to overflow at some point, so you will get unexpected results. Best to use a standard checksum algorithm or one of the already available classes such as CRC32 or Adler31. As for your code, you seem to be treating the result as an integer, so why cast to short in the first place?

Java does all arithmetic calculations using int's, so your bytes get converted to int and the ones that don't fit into a byte will look like this as int's: ffffffef (-17). Naturally you only need the actual byte value, so you need to zero out everything else using (0xff & b). So your loop than becomes something like this:

  int checkSum = 0;

  for(byte b : bytes){
    checkSum += (0xff & b);
  }
like image 24
Nikolay Elenkov Avatar answered Sep 30 '22 06:09

Nikolay Elenkov


byte according to Java Docs :

The value of a byte is ranged between 2^(-7) and (2^7)-1 (-128 to 127).

But your value 0xEF (in decimal 239) has already reached the limit of a byte. That's what cause the sum give the wrong numbers.

like image 23
Aprian Avatar answered Sep 30 '22 07:09

Aprian