最近在条码制作器新版中加入了EAN8,EAN13和UPC-A的校验位自动计算功能,实现的算法如下:
/* 不含校验位的EAN8,EAN13编码 */ public static int getEANCheckSUM(String EAN8orEAN13) { if(EAN8orEAN13.length() != 12) { EAN8orEAN13 = "00000" + EAN8orEAN13; //如果是EAN8条码,自动在前面补足5个0凑成EAN13来计算 } if(EAN8orEAN13.length() != 12) { return 0; } int c1 = 0; int c2 = 0; for(int i = 0; i<EAN8orEAN13.length(); i++) { int c = EAN8orEAN13.charAt(EAN8orEAN13.length() - i - 1) - '0'; if(i % 2 == 0) c1+=c; else c2+=c; } int cc = 10 - (c1 * 3 + c2)%10; if(cc==10) return 0; else return cc; } public static int getUPCACheckSUM(String UPCA) { if(UPCA.length() != 11) { return 0; } int c1 = 0; int c2 = 0; for(int i = 0; i<UPCA.length(); i++) { int c = UPCA.charAt(UPCA.length() - i - 1) - '0'; if(i % 2 == 0) c1+=c; else c2+=c; } int cc = 10 - (c1 * 3 + c2)%10; if(cc==10) return 0; else return cc; } |