Is there a method in c# that would talk the ip address 10.13.216.41
and display it as 00001010.00001101.11011000.00101001. If not, how can it be done?
Is there a method in c# that would talk the ip address 10.13.216.41
and display it as 00001010.00001101.11011000.00101001. If not, how can it be done?
While I won't rewrite the format-as-binary code (Larsenal's answer was fine), I'll point out that splitting on "." won't work for IPv6 addresses. If you use IPAddress.Parse, though, it will work for any address format. You can then use IPAddress.GetAddressBytes to get each part of the address.
So instead of:
input.Split('.').Select( ... )
do:
IPAddress.Parse(input).GetAddressBytes().Select( ... )
static string IPAddrToBinary( string input) {
// assumes a valid IP Address format
return String.Join(".", (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'))).ToArray());
}
Here's a version with comments, which may be a little easier to understand:
static string IPAddrToBinary(string input)
{
return String.Join(".", ( // join segments
input.Split('.').Select( // split segments into a string[]
// take each element of array, name it "x",
// and return binary format string
x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0')
// convert the IEnumerable<string> to string[],
// which is 2nd parameter of String.Join
)).ToArray());
}
Funny, I wrote a javascript version of this today for another question.
Here's the c# translation of that code:
int dottedQuadToInt(string ip)
{
var parts = ip.Split(new char[] {'.'}, 4);
if (parts.Length != 4) return -1;
var result = 0;
var bitPos = 1;
foreach(var part in parts)
{
//validation
if (part.Length == 0 || part.Length > 3) return -1;
int segment;
if (!int.TryParse(part, out segment) || segment<0 || segment > 255) return -1;
//compute next segment
result += bitPos * segment;
bitPos = bitPos << 8;
}
return result;
}
Now, this isn't exactly what you asked for, but it's arguably more useful and it shoudl point you in the right direction.
You could do:
var parts = (from p in ("10.13.216.41").Split('.')
select int.Parse(p)).ToArray();
string result = string.Format("{0}.{1}.{2}.{3}",
Convert.ToString(part[0], 2).PadLeft(8,'0'),
Convert.ToString(part[1], 2).PadLeft(8,'0'),
Convert.ToString(part[2], 2).PadLeft(8,'0'),
Convert.ToString(part[3], 2).PadLeft(8,'0'));
This method can help you:
static string IPDecToBinary(string IPAdresa)
{
string IPverBinare = null;
IPAddress IPDec = IPAddress.Parse(IPAdresa);
byte[] IPByte = IPDec.GetAddressBytes();
IPverBinare = string.Format("{0}.{1}.{2}.{3}",
Convert.ToString(IPByte[0], 2).PadLeft(8, '0'),
Convert.ToString(IPByte[1], 2).PadLeft(8, '0'),
Convert.ToString(IPByte[2], 2).PadLeft(8, '0'),
Convert.ToString(IPByte[3], 2).PadLeft(8, '0')
);
return IPverBinare;
}