COG-UK Docs

View the Project on GitHub COG-UK/docs

Updated 2020-03-20 by @khelwood

Validating a heron barcode

The barcode is made up of a prefix, followed by a hyphen, followed by a hexadecimal string, all in capitals. The prefix should be the one correct for the location the barcode is being used. The last digit of the hexadecimal string is a checksum calculated based on the preceding characters.

To validate the checksum

Example 1

SANG-4A996

The checksum is calculated from 4A99.

TOTAL = (9 + A) + (9 + 4) * 3 = 4A HEX (58 DEC)

Example 2

NIRE-102B1B

The checksum is calculated from 102B1.

TOTAL = (1 + 2 + 1) + (B + 0) * 3 = 25 HEX = 37 DEC
    // This Java code is equivalent to the description above, though
    // not following exactly the same steps.

    private static int hexCharToInt(char ch) {
        if (ch>='0' && ch<='9') return ch-'0';
        if (ch>='A' && ch<='F') return ch-'A'+10;
        throw new IllegalArgumentException("Illegal hex char: "+ch);
    }
    private static char intToHexChar(int n) {
        if ((n&0xf)!=n) {
            throw new IllegalArgumentException("Hex char out of range: "+n);
        }
        if (n<10) return (char) ('0'+n);
        return (char) ('A'+n-10);
    }

    // hex is the hex part of the barcode string (without the checksum)
    private static char calculateChecksum(String hex) {
        final int l = hex.length();
        int sum = 0;
        for (int i = 0; i < l; ++i) {
            int v = hexCharToInt(hex.charAt(l-1-i));
            if ((i&1)!=0) {
                v *= 3;
            }
            sum += v;
        }
        return intToHexChar((-sum)&0xf);
    }

Published 2020-03-19. Updated 2020-03-20. Page maintainer @khelwood.