-
-
Save pegasuskim/5bf1f62f6fc61ac4ab50d8fe445e6140 to your computer and use it in GitHub Desktop.
MRZ (Machine Readable Zone) checksum calculator
This file contains hidden or 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
import std.algorithm; | |
import std.range; | |
ubyte charCode(dchar c) pure { | |
switch (c) { | |
case '<': return 0; | |
case 'A': .. case 'Z': return cast(ubyte)(c - 'A' + 10); | |
case '0': .. case '9': return cast(ubyte)(c - '0'); | |
default: assert(0); | |
} | |
} | |
static assert(charCode('Z') == 35); | |
static assert(charCode('9') == 9); | |
int calcMrz(string data) pure { | |
return data | |
.map!(charCode) | |
.zip([7,3,1].cycle) | |
.fold!( (a,b) => a + b[0]*b[1] )(0) % 10; | |
} | |
static assert(calcMrz("AB2134<<<") == 5); | |
string calcField(string data) pure { | |
return data ~ cast(char)('0' + calcMrz(data)); | |
} | |
static assert(calcField("140910") == "1409105"); | |
void main(string[] args) { | |
import std.stdio; | |
writeln(args[1..$] | |
.map!(calcField) | |
.fold!( (a,b) => a~b ) | |
.calcField | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment