|
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionThis article serves to describe the algorithm used to calculate a UPS Tracking Number. It took me a while to figure this out, researching mostly. I thought I would make it a bit easier of others by describing it here. Using the codeThe following code is a generic method that can be used to calculate a check digit for a UPS Tracking Number. The input for the method is a String, but you could rework it to use a raw Char[] if wish. This method leaves the rest of the tracking number up to you. it takes a 15 character sequence, in this case a String, and calculates the check digit using this sequence. For information sake, I will describe how the company I work for generates tracking numbers. This is up to you, as only two portions are required by UPS, the rest you can make up on your own.
First of all you will notice that the described sequence above gives is 17 characters, where as we only need 15 to calculate the check digit. To do this, we drop the "1Z" portion, and only use the last 15 characters in the method. Next let me take a moment to outline the algorithm used to generate the check digit, then you'll see the method below the outline:
Here is the method: //
// UPS Check Digit Calculation Method
//
private int CalculateCheckDigit(String trk)
{
int checkdigit = 0;
char[] chars = trk.ToCharArray();
int charindex = 1;
int runningtotal = 0;
foreach(Char ch in chars)
{
if((charindex % 2) == 0) //Indicates character in even position
{
int testeven;
if(Int32.TryParse(ch.ToString(), out testeven) == true) // Indicates numeric value
{
runningtotal += (2 * testeven);
}
else // Indicates alpha value
{
int asciivalue = System.Convert.ToInt32(ch);
int n = asciivalue - 48;
runningtotal += n;
}
}
else // Indicates character in odd position
{
int testodd;
if(Int32.TryParse(ch.ToString(), out testodd) == true) // Indicates numeric value
{
runningtotal += testodd;
}
else // Indicates alpha value
{
int asciivalue = System.Convert.ToInt32(ch);
int n = asciivalue - 48;
int x = ((2 * n) - (9 * (int)(n / 5)));
runningtotal += x;
}
}
charindex++;
}
int x = (runningtotal % 10);
if(x == 0) checkdigit = x;
else if(x > 0) checkdigit = (10 - x);
return checkdigit;
}
|
||||||||||||||||||||||||||||||||||||||||||||||||||||