Hello !

I'm currently working on a school project where at one place in the project I'm suppost to make a program, which converts a binary ip adress to decimal.

The input format is either: 11111111 11110000 00000000 01111111
or 11111111111100000000000001111111

My main program, works as follow:

string iPAddress = "11111111111100000000000001111111";

Where the methods is:

    static public string IPAddressBinToDec(string iPAddress)
        string newiPAddress = ReWrite(iPAddress);
        return String.Join(".", (newiPAddress.Split('.').Select(x => Convert.ToInt32(x,2))));

    static public string ReWrite(string input)
        return Regex.Replace(input, "(.{8})", "$1.").Trim();

My problem was how i would handle if the input format was binary with spaces?: 11111111 11110000 00000000 01111111

Thanks for the help.


I also had problems validating wheither the input was in correct format or not, any tips there?

I would suggest you to split into array rather then adding a whitespace (you can still add a whitespace when you have an array);

    static void Main(string[] args)
        string iPAddress = "11111111111100000000000001111111";
        string[] ipSeperated = SplitString(iPAddress, 8);

    static string[] SplitString(string str, int size)
        return Enumerable.Range(0, str.Length / size)
                         .Select(i => str.Substring(i * size, size)).ToArray();

If you wanna add a white space you can do by using String.Join method.

    string newId = string.Join(" ", ipSeperated);

This is it.
Hope you like it.