Android Byte Array Checksum checkSum(byte[] data)

Here you can find the source of checkSum(byte[] data)

Description

check Sum

Declaration

public static short checkSum(byte[] data) 

Method Source Code

//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
    public static short checkSum(byte[] data) {
        long checksum = 0;
        for (byte d : data) {
            short element = 0;
            element |= 0x00FF & d;/*  ww  w  .ja  va2 s .c  o  m*/

            checksum += element;
        }

        return (short) (checksum & 0xFFFF);
    }

    public static int checkSum(File f) {
        long checksum = 0;
        try {
            FileInputStream fileImg = new FileInputStream(f);

            do {
                byte[] block = new byte[2];
                int size = fileImg.read(block);

                if (size != 2) {
                    break;
                }

                int val = bytes2short(block) & 0x0000FFFF;
                checksum += val;

            } while (true);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return 0;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }

        return (int) (checksum & 0xFFFFFFFF);
    }

    public static short bytes2short(byte[] data) {
        short val = 0;

        val |= data[0] & 0x00FF;
        val |= data[1] << 8;

        return val;
    }
}

Related

  1. checkSum2(byte[] data)
  2. checkSum(byte[] bytes)
  3. checkSum(byte[] cmdPackage)