Thursday, August 9, 2007

C# IP utilities : Decimal to binary notation

public string IPdec2binary(string ip)
{

string ret = "";
try
{
string[] theIP = ip.Split('.');

long na = Convert.ToInt64(theIP[0]);

long nb = Convert.ToInt64(theIP[1]);

long nc = Convert.ToInt64(theIP[2]);

long nd = Convert.ToInt64(theIP[3]);

string sa = Convert.ToString(na, 2);

string sb = Convert.ToString(nb, 2);

string sc = Convert.ToString(nc, 2);

string sd = Convert.ToString(nd, 2);


long a = Convert.ToInt64(sa);

long b = Convert.ToInt64(sb);

long c = Convert.ToInt64(sc);

long d = Convert.ToInt64(sd);



ret = Convert.ToString("" + a).PadLeft(8, '0') + ".";

ret += Convert.ToString("" + b).PadLeft(8, '0') + ".";

ret += Convert.ToString("" + c).PadLeft(8, '0') + ".";

ret += Convert.ToString("" + d).PadLeft(8, '0');
}
catch
{
return "";
}

return ret;
}

1 comment:

Sune Iversen said...

Very nice!

altho i really would like some comments to how this actually happens