4

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?

4
  • I'm curious - why would one do this? Commented Oct 1, 2009 at 18:30
  • 1
    So I won't have to do it by hand. Commented Oct 1, 2009 at 18:44
  • I mean...why need the IP address in binary-ish format? Commented Oct 1, 2009 at 19:38
  • Oh, I was just messing around with using it with the subnet mask to get my host and network id. Commented Oct 1, 2009 at 20:51

6 Answers 6

10

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( ... )
Sign up to request clarification or add additional context in comments.

Comments

7
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());
}

3 Comments

What order is it calling the methods here? i am not familiar with lambda syntax, so I am unsure.
Split -> Foreach -> Convert.ToString -> ToArray -> String.Join
Thanks Richard. Still trying to get familiar with LINQ.
1

First, you would need to get the number you want to convert to binary (using String.Split, for example). Then, you can use an overload of the Convert.ToString method to return a string of the specified number in the specified base. For example:

Convert.ToString (128, 2);

returns

10000000

Comments

0

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.

2 Comments

Just because it's more useful he should use it? Not trying to be a troll, but you have gold-plated the functionality he asked for. Additionally, it returns an int, and not a string.
This translation is not complete it seems. TryParse does not take only 1 argument and base is a reserved keyword in c#.
0

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'));

2 Comments

I can't find the split method on string. It doesn't popup with intellisense.
You updated it as well because I was able to use split on a variable of type string, but not directly on the string type.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.