今天用C#寫了一個身分證驗證程式,因為剛學可能寫得不好,如果哪邊可以改進請大家告知一下,謝謝!
public static bool CheckID(string sid)
{
string[] sid_array = new string[10];
int[] int_array = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 };
if (sid.Length != 10)
{
return false;
}
else
{
sid = sid.ToUpper();
for (int i = 0; i <= (sid.Length - 1); i++)
{
sid_array[i] = sid.Substring(i, 1);
}
int first_array = (ascii(sid_array[0]) - 65);
int checktotal = Convert.ToInt16(int_array[first_array].ToString().Substring(0, 1)) + (Convert.ToInt16(int_array[first_array].ToString().Substring(1, 1)) * 9);
for (int j = 1; j < 9; j++)
{
checktotal = checktotal + Convert.ToInt16(sid_array[j]) * (9 - j);
}
int checksum = (checktotal % 10);
if (checksum == 0)
{
checksum = 0;
}
else
{
checksum = int_array[first_array] - checksum;
}
if (checksum == Convert.ToInt16(sid_array[9]))
{
return true ;
}
else
{
return false;
}
}
}
下面的部分是類似VB ASC函數的功能,因為我找不到C#要如何寫,這是在網路上找到的
http://blog.csdn.net/hongsejiaozhu/archive/2008/03/03/2142473.aspx
public static int ascii(string chr)
{
Encoding ecode = Encoding.GetEncoding("big5");
byte[] codebytes = ecode.GetBytes(chr.ToString());
if (istwobyteschar(chr))
{
return (int)codebytes[0] * 256 + (int)codebytes[1] - 65536;
}
else
{
return (int)codebytes[0];
}
}
public static bool istwobyteschar(string chr)
{
string str = chr.ToString();
Encoding ecode = Encoding.GetEncoding("big5");
if (ecode.GetByteCount(str) == 2)
{
return true;
}
else
{
return false;
}
}
留言列表