Verhoeff Algorithm in Delphi

Oct 29, 2016

I needed an implementation of the Verhoeff check digit algorithm in Delphi, and couldn’t find one. So reproduced here for ease of use by anyone else who needs it: ```` const verhoeff_d : array[0..9,0..9] of integer = ( (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 2, 3, 4, 0, 6, 7, 8, 9, 5), (2, 3, 4, 0, 1, 7, 8, 9, 5, 6), (3, 4, 0, 1, 2, 8, 9, 5, 6, 7), (4, 0, 1, 2, 3, 9, 5, 6, 7, 8), (5, 9, 8, 7, 6, 0, 4, 3, 2, 1), (6, 5, 9, 8, 7, 1, 0, 4, 3, 2), (7, 6, 5, 9, 8, 2, 1, 0, 4, 3), (8, 7, 6, 5, 9, 3, 2, 1, 0, 4), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0) ); // The permutation table verhoeff_p : array[0..7,0..9] of integer = ( (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 5, 7, 6, 2, 8, 3, 0, 9, 4), (5, 8, 0, 3, 7, 9, 6, 1, 4, 2), (8, 9, 1, 6, 0, 4, 3, 5, 2, 7), (9, 4, 5, 3, 1, 2, 6, 8, 7, 0), (4, 2, 8, 6, 5, 7, 3, 9, 0, 1), (2, 7, 9, 3, 8, 0, 6, 4, 1, 5), (7, 0, 4, 6, 9, 1, 3, 2, 5, 8) ); //The inverse table verhoeff_inv : array [0..9] of char = (‘0’, ‘4’, ‘3’, ‘2’, ‘1’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’);

//For a given number generates a Verhoeff digit function genCheckDigit(s : String): char; var i, c, len : integer; begin c := 0; s := s + ‘0’; len := length(s);

for i := len downto 1 do c := verhoeff_d[c][verhoeff_p[((len-i) mod 8)][ord(s[i]) - ord(‘0’)]];

result := verhoeff_inv[c]; end;

////Validates that an entered number is Verhoeff compliant. ////The check digit must be the last one. procedure validateCheckDigit(s : String); var i, c, len : integer; begin c := 0; len := length(s);

for i := len downto 1 do c := verhoeff_d[c][verhoeff_p[((len-i) mod 8)][ord(s[i]) - ord(‘0’)]];

if c <> 0 then raise Exception.Create(‘Check digit error: “‘+s+’” is not valid by Verhoeff algorithm’); end;

````