C# IPV4字串轉整數 在 32位元與64位元的差異
C# IPV4字串轉整數 在 32位元與64位元的差異
EX:
192.168.1.190
-1107187520 (32)-> 11111111111111111111111111111111 10111110000000011010100011000000(WIN7小算盤)
+3187779776 (64)-> 00000000000000000000000000000000 10111110000000011010100011000000(WIN7小算盤)
程式:
String StrIP = “192.168.1.190”;
int intIP = 0;
intIP = HW_Net_API.ip2long32(StrIP, true);
StrIP = HW_Net_API.long2ip32(intIP, true);
StrIP = HW_Net_API.long2ip(intIP, true);
long lngIP = HW_Net_API.ip2long(StrIP, true);
//———————————————–//
public static Int32 ip2long32(String ip, bool Reversal = false)
{
String[] ips = ip.Split(‘.’);
Int32 num = 0;
if (!Reversal)
{
num = (Int32)(16777216L * Convert.ToInt64(ips[0], 10) + 65536L * Convert.ToInt64(ips[1], 10) + 256 * Convert.ToInt64(ips[2], 10) + Convert.ToInt64(ips[3], 10));
}
else
{
num = (Int32)(16777216L * Convert.ToInt64(ips[3], 10) + 65536L * Convert.ToInt64(ips[2], 10) + 256 * Convert.ToInt64(ips[1], 10) + Convert.ToInt64(ips[0], 10));
}
return num;
}
public static String long2ip32(Int32 ipLong, bool Reversal = false)
{
//long ipLong = 1037591503;
Int64[] mask = new Int64[] { 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 };
Int64 num = 0;
string Buf = “”;
for (int i = 0; i < 4; i++)
{
num = (ipLong & mask[i]) >> (i * 8);
if (!Reversal)
{
Buf = “.” + num + Buf;
}
else
{
Buf += num + “.”;
}
}
if (!Reversal)
{
Buf = Buf.Substring(1);
}
else
{
Buf = Buf.Substring(0, Buf.Length – 1);
}
return Buf;
}
public static Int64 ip2long(String ip, bool Reversal = false)
{
String[] ips = ip.Split(‘.’);
Int64 num = 0;
if (!Reversal)
{
num = 16777216L * Convert.ToInt64(ips[0], 10) + 65536L * Convert.ToInt64(ips[1], 10) + 256 * Convert.ToInt64(ips[2], 10) + Convert.ToInt64(ips[3], 10);
}
else
{
num = 16777216L * Convert.ToInt64(ips[3], 10) + 65536L * Convert.ToInt64(ips[2], 10) + 256 * Convert.ToInt64(ips[1], 10) + Convert.ToInt64(ips[0], 10);
}
return num;
}
public static String long2ip(Int64 ipLong, bool Reversal = false)
{
//long ipLong = 1037591503;
Int64[] mask = new Int64[] { 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 };
Int64 num = 0;
string Buf = “”;
for (int i = 0; i < 4; i++)
{
num = (ipLong & mask[i]) >> (i * 8);
if (!Reversal)
{
Buf = “.” + num + Buf;
}
else
{
Buf += num + “.”;
}
}
if (!Reversal)
{
Buf = Buf.Substring(1);
}
else
{
Buf = Buf.Substring(0, Buf.Length – 1);
}
return Buf;
}