Last active
February 17, 2023 02:40
-
-
Save magicianlib/1fd753f2f37be24cb4a88909d7a6a039 to your computer and use it in GitHub Desktop.
检查身份证号码合法性
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
import "math" | |
// VerifyChineseMainlandIdCard 检查身份证号码合法性 | |
// | |
// Wikipedia: | |
// https://zh.wikipedia.org/wiki/中华人民共和国公民身份号码 | |
// | |
// China gov: | |
// http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm | |
// | |
func VerifyChineseMainlandIdCard(id []byte) bool { | |
if len(id) != 18 { | |
return false | |
} | |
var idx, sum, check_code int | |
for ; idx < 17; idx++ { | |
// (pow(2, 17 - index) % 11) * (id[index] - '0) | |
sum += (int(math.Pow(float64(2), float64(17-idx))) % 11) * int(id[idx]-'0') | |
} | |
check_code = (12 - (sum % 11)) % 11 | |
if check_code < 10 { | |
return check_code == int(id[17]-'0') | |
} else { | |
return id[17] == 'X' || id[17] == 'x' | |
} | |
} |
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
func TestVerifyChineseMainlandIdCard(t *testing.T) { | |
var ids = [][]byte{ | |
// male | |
[]byte("11010119900307125X"), | |
[]byte("110101199003070492"), | |
[]byte("110101199003077053"), | |
[]byte("110101199003075293"), | |
[]byte("110101199003077010"), | |
// female | |
[]byte("110101199003078451"), | |
[]byte("110101199003075234"), | |
[]byte("110101199003070177"), | |
[]byte("11010119900307977X"), | |
[]byte("110101199003078339"), | |
} | |
for _, id := range ids { | |
t.Logf("%s checked: %t\n", id, VerifyChineseMainlandIdCard(id)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment