Snippets

Zhiwei Li Luhn Algo in C#(for IMEI/ICCID checksum)

Created by Zhiwei Li
using System;

namespace iccid
{
	public static class Luhn{
		public static int CalcChecksum(string id){
			int currentDigit ;
			int idSum = 0 ;
			int currentProcNum = 0 ;

			id = id + '0';
			int idLength = id.Length ;

			if ((idLength != 20) && (idLength != 15)) {
				throw new System.ArgumentException ("length not 19 or 14");
			}

			for(int i=idLength-1; i>=0; i--){
				string idCurrentRightmostDigit = id.Substring(i,1);

				if (!int.TryParse (idCurrentRightmostDigit, out currentDigit)) {
					throw new System.ArgumentException ("not digital");
				}

				if(currentProcNum%2 != 0){
					if((currentDigit*= 2) > 9)
						currentDigit-= 9 ;
				}
				currentProcNum++ ; 

				idSum += currentDigit ;
			}

			currentDigit = idSum%10;
			if (currentDigit != 0) {
				currentDigit = 10 - currentDigit;
			}

			return currentDigit;
		}
	}
		
	class MainClass
	{
		public static void Main (string[] args)
		{
			string iccid = "8986011101510022556";
			Console.WriteLine (Luhn.CalcChecksum(iccid));
		}
	}
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.