Java Glossary : check digit

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : C words : check digit.

check digit
Dating back to keypunches, id numbers have an appended check digit used to ensure that the number was keyed properly. The various types of bar code such as the UPC you see on grocery items all have a check digit. The basic idea is if you transpose or mistype a character in entering a number the checksum won't match the one that should be there according to the calculations. One of the most common schemes is called mod 10, used for all credit card numbers and the Canadian SIN (Social Insurance Number). The Stiles site maintains pointers to all kinds of information related to check digits. Here is how to calculate a mod 10 check digit by the manual method:

e.g. to compute the expected check digit 7 for: 706-511-22?

digit 7 0 6 5 1 1 2 2 ?
multiplier 1 2 1 2 1 2 1 2  
result 7 0 6 10
1
1 2 2 4   horizonal sum = 23
23 MOD 10 = 3
10 - 3 = 7 -- the check digit

Note that the two digits of the multiplication results must be added before doing the sum.

Here is method more amenable to computer calculation:

e.g. to compute see if the check digit is as expected: 706-511-227

digit 7 0 6 5 1 1 2 2 7
multiplier 1 z 1 z 1 z 1 z 1
result 7 0 6 1 1 2 2 4 7 horizonal sum = 30
30 MOD 10 had better = 0. What do you know, it is.
Here is the Java code to do this where z is a function that doubles and adds digits, defined mathematically more efficiently as:

/**
 * Validate checkdigit of 9 digit number,
 * e.g. Canadian SIN Number.
 * input is in ints d1..d9 as ints, not chars.
 *
 * @return true if checkdigit is as expected.
 */
boolean isCheckDigitValid()
   {
   int weightedSumOfDigits = d1 + z ( d2 ) + d3 + z ( d4 ) + d5 + z ( d6 ) + d7 +z ( d8 ) + d9;
   return weightedSumOfDigits % 10 == 0;
   }

private int z ( int digit)
   {
   // 0->0 1->2 2->4 3->6 4->8 5->10->1 6->12->3 7->14->5 8->16->7 9->18->9
   if ( digit == 9 ) return 9;
   else return( digit * 2 ) % 9;
   }


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 2392.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/checkdigit.html J:\mindprod\jgloss\checkdigit.html