以下几种算法暂时不知道那种算法效率最快,请高手分析一下。
转载请注明出处:SQL吧技术先锋
www.sql8.net
http://www.sql8.net/showtopic-414.aspx
作者:杨小勇
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(“ip1:” + numtoip1(520193) + “<BR>”);
Response.Write(“ip2:” + numtoip2(2130706433) + “<BR>”);
Response.Write(“iptonum1:” + iptonum1(“127.0.0.1”) + “<BR>”);
Response.Write(“iptonum2:” + iptonum2(“127.0.0.1”) + “<BR>”);
}
//网上一仁兄的代码很简洁不过再测试192.168.0.1/127.0.0.1等会出现错误,其它大部测试无误不知道为什么,也没有去研究透望高手指点yxy
private long iptonum1(string Ip)
{
//取出IP地址去掉‘.’后的string数组
string[] Ip_List = Ip.Split(“.”.ToCharArray());
string X_Ip = “”;
//循环数组,把数据转换成十六进制数,并合并数组(3dafe81e)
foreach (string ip in Ip_List)
{
X_Ip += Convert.ToInt16(ip).ToString(“x”);
}
//将十六进制数转换成十进制数
long N_Ip = long.Parse(X_Ip, System.Globalization.NumberStyles.HexNumber);
return N_Ip;
} //按标准 219*256*256*256+159*256*256+68*256+54=3684647990 写出的代码yxy
private long iptonum2(string Ip)
{
//取出IP地址去掉‘.’后的string数组
string[] Ip_List = Ip.Split(“.”.ToCharArray());
string X_Ip = “”;
long N_Ip=0;
for (int i = 0; i<=Ip_List.Length-1; i++)
{
//Response.Write(“a” + i.ToString() + “:” + Ip_List[i].ToString()+”<BR>”); //测试用yxy
N_Ip = N_Ip+( Convert.ToInt64(System.Math.Pow(256, 3 – i)) * int.Parse(Ip_List[i].ToString()));
} return N_Ip;
} //按标准 219*256*256*256+159*256*256+68*256+54=3684647990 逆转算法yxy
private string numtoip1(long num)
{
string str = “”;
long k;
for (int i = 0; i <= 3; i++)
{
k = (num) / Convert.ToInt32(System.Math.Pow(256, i)) % 256;
str = k.ToString() + str;
if (i < 3)
{
str = “.” + str;
}
}
return str.ToString();
} //使用.net命名空间IPAddress类型将数值转成IPyxy
private string numtoip2(long num)
{
string str = “”;
IPAddress ip = new IPAddress(num);
string[] a = new string[3];
a = ip.ToString().Split(‘.’);
for (int i = 0; i <= 3; i++)
{
str = a[i].ToString() + str;
if (i < 3)
{
str = “.” + str;
}
} return str;
}