Calculates the checksum of an byte array. - Java java.lang

Java examples for java.lang:byte Array

Description

Calculates the checksum of an byte array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int begin = 2;
        int end = 2;
        System.out.println(calcChecksum(data, begin, end));
    }//from   w  w w . j a  v a 2  s  .c  o  m

    /**
     * Calculates the checksum of an byte array.
     *
     * @param data the byte array
     * @param begin the start index
     * @param end the end index
     * @return the calculated checksum
     */
    public static int calcChecksum(byte[] data, int begin, int end) {
        // sum content bytes
        int sum = 0;
        for (int i = begin; i < end; i++) {
            sum += byteToInt(data[i]);
        }
        return sum;
    }

    /**
     * Converts a unsigned byte to an signed int value.
     *
     * @param b a byte
     * @return the byte as int value
     */
    public static int byteToInt(byte b) {
        return (int) b & 0x00000000FF;
    }
}

Related Tutorials