Last active
April 3, 2017 09:45
-
-
Save number23/4368396 to your computer and use it in GitHub Desktop.
HK id card check digit
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
public boolean hkid_check_digit(String id){ | |
if (id.matches("[A-Z]\\d{6}-[\\d|A]") == false) { | |
msgMgr.reportException("身份証號格式錯誤,X123456-X", true); | |
return false; | |
} | |
/* | |
* check digit, A=10, B=11, ... Z=35 | |
* the 9th weight == 36, google: another one is 58. | |
* | |
* check digit formula: ISBN-10 | |
* http://zh.wikipedia.org/wiki/%E5%9B%BD%E9%99%85%E6%A0%87%E5%87%86%E4%B9%A6%E5%8F%B7#10.E4.BD.8D | |
*/ | |
char ch = id.charAt(0); | |
int first = (int)ch; | |
int S = (36 * 9) + ((first - 55) * 8); | |
int idx = 7; | |
for (int i = 1; i <= 6; i++) { | |
ch = id.charAt(i); | |
int j = (int)ch; | |
j = j - 48; | |
S += j * idx; | |
idx--; | |
} | |
int M = S % 11; | |
int N = 11 - M; | |
if (N == 10) N = 17; // ch = 'A', 65 - 48 == 17 | |
if (N == 11) N = 0; // ch = '0' | |
ch = id.charAt(8); | |
int check_digit = (int)ch; | |
check_digit = check_digit - 48; | |
if (N != check_digit) { | |
msgMgr.reportException("無效的香港身份証號碼", true); | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这是java语言?