Skip to content

Instantly share code, notes, and snippets.

@number23
Last active April 3, 2017 09:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save number23/4368396 to your computer and use it in GitHub Desktop.
Save number23/4368396 to your computer and use it in GitHub Desktop.
HK id card check digit
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;
}
@Lalala117
Copy link

这是java语言?

@yiukalun
Copy link

yiukalun commented Apr 3, 2017

不支援雙字母開頭的身分證號碼.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment