EAN 8: Como calcular o dígito de soma de verificação?
Pergunta
Preciso criar o código de barras EAN 8 programaticamente. Eu procuro um algoritmo para calcular o dígito de soma de verificação.
Solução
int checkSum(const std::vector<int>& code) const
{
if (code.size() < 8) return false;
for( SIZE_T i = 0; i< code.size(); i++ )
{
if( code[i] < 0 ) return false;
}
int sum1 = code[1] + code[3] + code[5]
int sum2 = 3 * (code[0] + code[2] + code[4] + code[6]);
int checksum_value = sum1 + sum2;
int checksum_digit = 10 - (checksum_value % 10);
if (checksum_digit == 10) checksum_digit = 0;
return checksum_digit;
}
Outras dicas
O algoritmo é coberto neste Artigo da Wikipedia sobre EAN, observe que o EAN-8 é calculado da mesma maneira que o EAN-13.
Aqui está um exemplo trabalhado de http://www.barcodeisland.com/ean8.phtml :
Supondo que desejemos codificar a mensagem de 7 dígitos "5512345", calcularíamos a soma de verificação da seguinte maneira:
Barcode 5 5 1 2 3 4 5
Odd/Even Pos? O E O E O E O
Weighting 3 1 3 1 3 1 3
Calculation 5*3 5*1 1*3 2*1 3*3 4*1 5*3
Weighted Sum 15 5 3 2 9 4 15
O total é 15 + 5 + 3 + 2 + 9 + 4 + 15 = 53. 7 deve ser adicionado a 53 para produzir um número uniformemente divisível por 10, portanto o dígito da soma de verificação é 7 e o valor do código de barras concluído é "55123457" .
string code="55123457";
int sum1 = code[1] + code[3] + code[5]
int sum2 = 3 * (code[0] + code[2] + code[4] + code[6]);
int checksum_value = sum1 + sum2;
int checksum_digit = 10 - (checksum_value % 10);
if (checksum_digit == 10)
checksum_digit = 0;
Desculpe pela reabertura
Versão Java
public int checkSum(String code){
int val=0;
for(int i=0;i<code.length();i++){
val+=((int)Integer.parseInt(code.charAt(i)+""))*((i%2==0)?1:3);
}
int checksum_digit = 10 - (val % 10);
if (checksum_digit == 10) checksum_digit = 0;
return checksum_digit;
}
Reparado com uma versão C#:
public static bool IsValidEan13(string eanBarcode)
{
return IsValidEan(eanBarcode, 13);
}
public static bool IsValidEan12(string eanBarcode)
{
return IsValidEan(eanBarcode, 12);
}
public static bool IsValidEan14(string eanBarcode)
{
return IsValidEan(eanBarcode, 14);
}
public static bool IsValidEan8(string eanBarcode)
{
return IsValidEan(eanBarcode, 8);
}
private static bool IsValidEan(string eanBarcode, int length)
{
if (eanBarcode.Length != length) return false;
var allDigits = eanBarcode.Select(c => int.Parse(c.ToString(CultureInfo.InvariantCulture))).ToArray();
var s = length%2 == 0 ? 3 : 1;
var s2 = s == 3 ? 1 : 3;
return allDigits.Last() == (10 - (allDigits.Take(length-1).Select((c, ci) => c*(ci%2 == 0 ? s : s2)).Sum()%10))%10;
}
Aqui está uma versão MySQL para EAN13:
SET @first12digits="123456789012";
SELECT @first12digits,
IF (
(@check:=10-MOD(
(CAST(SUBSTRING(@first12digits, 1, 1) AS DECIMAL))+
(CAST(SUBSTRING(@first12digits, 2, 1) AS DECIMAL) * 3)+
(CAST(SUBSTRING(@first12digits, 3, 1) AS DECIMAL))+
(CAST(SUBSTRING(@first12digits, 4, 1) AS DECIMAL) * 3)+
(CAST(SUBSTRING(@first12digits, 5, 1) AS DECIMAL))+
(CAST(SUBSTRING(@first12digits, 6, 1) AS DECIMAL) * 3)+
(CAST(SUBSTRING(@first12digits, 7, 1) AS DECIMAL))+
(CAST(SUBSTRING(@first12digits, 8, 1) AS DECIMAL) * 3)+
(CAST(SUBSTRING(@first12digits, 9, 1) AS DECIMAL))+
(CAST(SUBSTRING(@first12digits, 10, 1) AS DECIMAL) * 3)+
(CAST(SUBSTRING(@first12digits, 11, 1) AS DECIMAL))+
(CAST(SUBSTRING(@first12digits, 12, 1) AS DECIMAL) * 3)
,10)) = 10, 0, @check
) AS checkDigit;
Havia um bug. Se o calc resultado = 10, verifique o dígito = 0.
Aqui abaixo de uma versão melhor para o EAN14.
SET @first13digits="1234567890123";
SELECT @txCode13:=@first13digits,
@iCheck := (
10 - (
(
MID(@txCode13, 2, 1) +
MID(@txCode13, 4, 1) +
MID(@txCode13, 6, 1) +
MID(@txCode13, 8, 1) +
MID(@txCode13, 10, 1) +
MID(@txCode13, 12, 1)
) + (
MID(@txCode13, 1, 1) +
MID(@txCode13, 3, 1) +
MID(@txCode13, 5, 1) +
MID(@txCode13, 7, 1) +
MID(@txCode13, 9, 1) +
MID(@txCode13, 11, 1) +
MID(@txCode13, 13, 1)
) * 3 ) % 10
) AS iCheck,
@iCheckDigit := IF(@iCheck = 10, 0, @iCheck) AS checkDigit,
CONCAT(@t
xCode13, CAST(@iCheckDigit AS CHAR)) AS EAN14WithCheck
Aqui está a versão Java para EAN13
private int calcChecksum(String first12digits) {
char[] char12digits = first12digits.toCharArray();
int[] ean13 = {1,3};
int sum = 0;
for(int i = 0 ; i<char12digits.length; i++){
sum += Character.getNumericValue(char12digits[i]) * ean13[i%2];
}
int checksum = 10 - sum%10;
if(checksum == 10){
checksum = 0;
}
return checksum;
}
class GTIN(object):
def __init__(self, barcode=''):
self.barcode = barcode
def __checkDigit(self, digits):
total = sum(digits) + sum(map(lambda d: d*2, digits[-1::-2]))
return (10 - (total % 10)) % 10
def validateCheckDigit(self, barcode=''):
barcode = (barcode if barcode else self.barcode)
if len(barcode) in (8,12,13,14) and barcode.isdigit():
digits = map(int, barcode)
checkDigit = self.__checkDigit( digits[0:-1] )
return checkDigit == digits[-1]
return False
def addCheckDigit(self, barcode=''):
barcode = (barcode if barcode else self.barcode)
if len(barcode) in (7,11,12,13) and barcode.isdigit():
digits = map(int, barcode)
return barcode + str(self.__checkDigit(digits))
return ''
Hoje preciso de uma versão PHP, lembro -me de esta página e copio da versão Java. Obrigada.
function getEAN13($txEan12)
{
$iVal=0;
for($i=0; $i<strlen($txEan12); $i++)
{
$iSingleCharVal = intval(substr($txEan12, $i, 1)); // extract value of one char
$iSingleCharMult = $iSingleCharVal * ($i%2==0 ? 1 : 3); // calculate depending from position
$iVal+= $iSingleCharMult; // sum
}
$iCheckDigit = 10 - ($iVal % 10);
if ($iCheckDigit == 10) $iCheckDigit = 0;
return $txEan12 . $iCheckDigit;
}
Versão Java:
Funciona perfeitamente
public static int checkSum(String code){
int val=0;
for(int i=0; i<code.length()-1; i++){
val+=((int)Integer.parseInt(code.charAt(i)+""))*((i%2==0)?1:3);
}
int checksum_digit = (10 - (val % 10)) % 10;
return checksum_digit;
}
Cálculo do dígito de verificação Python EAN13 com base na função Java de Najoua Mahi:
def generateEAN13CheckDigit(self, first12digits):
charList = [char for char in first12digits]
ean13 = [1,3]
total = 0
for order, char in enumerate(charList):
total += int(char) * ean13[order % 2]
checkDigit = 10 - total % 10
if (checkDigit == 10):
return 0
return checkDigit
Isso funciona em ambos Ean 13 e Ean8:
public static String generateEAN(String barcode) {
int first = 0;
int second = 0;
if(barcode.length() == 7 || barcode.length() == 12) {
for (int counter = 0; counter < barcode.length() - 1; counter++) {
first = (first + Integer.valueOf(barcode.substring(counter, counter + 1)));
counter++;
second = (second + Integer.valueOf(barcode.substring(counter, counter + 1)));
}
second = second * 3;
int total = second + first;
int roundedNum = Math.round((total + 9) / 10 * 10);
barcode = barcode + String.valueOf(roundedNum - total);
}
return barcode;
}
Este é um código que escrevi no VFP (Visual FoxPro 9), para EAN-8 e EAN-13
Lparameters lcBarcode,llShowErrorMessage
If Vartype(m.lcBarcode)<>'C'
If m.llShowErrorMessage
MessageBox([Type of parameter is incorect!],0+16,[Error Message])
EndIf
Return .f.
EndIf
If Len(Chrtran(Alltrim(m.lcBarcode),[0123456789],[]))>0
If m.llShowErrorMessage
MessageBox([Provided barcode contains invalid characters!],0+16,[Error Message])
EndIf
Return .f.
EndIf
If Len(Alltrim(m.lcBarcode))=0
If m.llShowErrorMessage
MessageBox([The length of provided barcode is 0 (zero)!],0+16,[Error Message])
EndIf
Return .f.
EndIf
If !InList(Len(Alltrim(m.lcBarcode)),8,13)
If m.llShowErrorMessage
MessageBox([Provided barcode is not an EAN-8 or EAN-13 barcode!],0+16,[Error Message])
EndIf
Return .f.
EndIf
Local lnCheck as Integer, lnSum as Integer, lnOriginalCheck as Integer,jj as Integer
jj=0
lnSum=0
m.lnOriginalCheck = Cast(Right(Alltrim(m.lcBarcode),1) as Integer)
m.lcBarcode = Left(Alltrim(m.lcBarcode),Len(Alltrim(m.lcBarcode))-1)
For ii = Len(m.lcBarcode) to 1 step -1
jj=jj+1
lnSum = lnSum + Cast(Substr(m.lcBarcode,ii,1) as Integer) * Iif(Mod(jj,2)=0,1,3)
Next
lnCheck = 10-Mod(lnSum,10)
lnCheck = Iif(lnCheck =10,0,lnCheck)
Return (lnCheck = lnOriginalCheck)
Versão JavaScript para EAN-8 e EAN-13
function checksum(code) {
const sum = code.split('').reverse().reduce((sum, char, idx) => {
let digit = Number.parseInt(char);
let weight = (idx + 1) % 2 === 0 ? 1 : 3;
let partial = digit * weight;
return sum + partial;
}, 0);
const remainder = sum % 10;
const checksum = remainder ? (10 - remainder) : 0;
return checksum;
}