|
Checksums and Cyclic Redundancy Checks
An Introduction with Examples in Java |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
/**
* Add a string to a checksum
*
* @param s The string
* @param checksum The original checksum
* @returns The new checksum
*/
protected static int addToChecksum(String s, int checksum)
{
int current, i, length;
length = s.length();
for (i=0; i <= length-1; i++) {
current = (int)(s.charAt(i)); // Get a char
checksum ^= current; // xor the char into the checksum
}
return checksum;
}
/**
* Determine the checksum for a string
*
* @param s The string
* @returns The checksum
*/
protected static int calculateChecksum(String s)
{
return addToChecksum(s, 0);
}
/**
* Determine if a String has the proper checksum
*
* @param s The string
* @param crcString The proper checksum (in hex)
* @returns true if proper and false otherwise
*/
public static boolean check(String s, String crcString)
{
int actual, desired;
actual = calculateChecksum(s);
desired = HexFormat.fromHexDigits(crcString);
return (actual == desired);
}
package io;
import java.util.*;
import convert.Hex;
/**
* An example that uses the Checksum class
*
* @author Prof. David Benrstein, James Madison University
* @version 1.0
*/
public class ChecksumDriver
{
/**
* The entry point of the application
*
* @param args The command line arguments
*/
public static void main(String[] args)
{
boolean ok;
int validationValue;
String checkValue, gpgga, token;
StringTokenizer tokenizer;
// An NMEA message from a GPS receiver
gpgga = "$GPGGA,210230,3855.4487,N,09446.0071,W,"+
"1,07,1.1,370.5,M,-29.5,M,,*7A";
checkValue = "";
validationValue = 0;
tokenizer = new StringTokenizer(gpgga, "$,");
while (tokenizer.hasMoreElements())
{
token = (String)(tokenizer.nextElement());
if (token.substring(0,1).equals("*"))
{
// The validation value (7A in the String above)
checkValue = token.substring(1);
}
else
{
// The check value
validationValue = Checksum.addToChecksum(token, validationValue);
}
}
ok = (validationValue == Hex.hexStringToInt(checkValue));
if (ok) System.out.println("It's good!");
else System.out.println("No good!");
}
}