IMEI not passing Luhn Checksum

468 views Asked by At

I have the following code for validating IMEIs (not SV)

public static boolean luhnc(char[] digits) {
    int sum = 0, s = 0;
    for (int i = 0; i < digits.length - 1; i += 2) {
        s = (digits[i+1] - '0') * 2;
        sum += (s > 10 ? s - 9 : s) + (digits[i] - '0');
    }
    return 10 - (sum % 10) == (digits[digits.length-1] - '0');
}

Almost every IMEI checks out except for my Samsung Galaxy Note 4.

I do not want to post it here for obvious reasons but at the same time I need someone to verify that it works.

Perhaps it's my implementation that's not right.

Please help.

2

There are 2 answers

2
azro On BEST ANSWER

There is a point you miss in Luhn algo after do the *2 operation, it's

  • if the number is >=10 (and not >), because 10 becomes 0 instead of 1

So fix like this (I extract it in a new line to be clear for you) :

for (int i = 0; i < digits.length - 1; i += 2) {
    s = (digits[i + 1] - '0') * 2;                 
    sum += (s >= 10 ? s - 9 : s) + (digits[i] - '0');
}

Also I would recommand to use a int[] instead of char[] to remove the - '0' everywhere

0
JackPGreen On

Another alternative is to use the library from Apache Commons.

org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(imei)