-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
30 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,38 @@ | ||
package cont | ||
|
||
// CalcCheckDigit calculates check digit for owner, equipment category ID and serial number. | ||
// This function was optimized for fun and has a suboptimal reading experience. | ||
func CalcCheckDigit(ownerCode string, equipCatID rune, serialNum int) int { | ||
n := 0 | ||
d := 1 | ||
var n uint16 = 0 | ||
var d uint16 = 1 | ||
|
||
for _, c := range ownerCode { | ||
n += d * charValue(c) | ||
n += d * charValue(uint16(c)) | ||
d *= 2 | ||
} | ||
n += d * charValue(equipCatID) | ||
d *= 2 | ||
divider := 100000 | ||
for divider > 0 { | ||
n += d * ((serialNum / divider) % 10) | ||
d *= 2 | ||
divider /= 10 | ||
|
||
n += d * charValue(uint16(equipCatID)) | ||
|
||
// Handle the case for the serial number when it is | ||
// out of range of uint16. | ||
n += 512 * uint16(serialNum%10) | ||
serialNum /= 10 | ||
n += 256 * uint16(serialNum%10) | ||
|
||
// uint16 can be used because we are now <10000 | ||
s := uint16(serialNum / 10) | ||
d = 128 | ||
for d >= 16 { | ||
n += d * (s % 10) | ||
d /= 2 | ||
s /= 10 | ||
} | ||
return n % 11 | ||
return int(n % 11) | ||
} | ||
|
||
// charValue returns the index of character plus 10. | ||
// A?BCDEFGHIJK?LMNOPQRSTU?VWXYZ | ||
// A=10, B=12, C=13, ... , K=21, L=23, ... | ||
func charValue(char rune) int { | ||
n := int(char) | ||
return n - 55 + (n-56)/10 | ||
// A=10, (no 11) B=12, C=13, ... , K=21, (no 22) L=23, ... | ||
func charValue(char uint16) uint16 { | ||
return char - 55 + (char-56)/10 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters