Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey,

so I'm currently working on a side project to get into programming and find myself at the point where I often have to look online for solutions. Which is, generally speaking, not a problem because I can usually learn from those things.

This time however I find myself opposite a one-line solution that has a lot of steps cluttered into one statement. I've already tried breaking it down into the single steps it would take -- without much success because it's very hard to read and process, at least for me.

So I wondered, what would the ideal way be of going about this?

C#
return String.Join(".", (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'))).ToArray());


This is the one liner I'm talking about.

What I have tried:

I've tried breaking it up myself for a while, without much success.
Posted
Updated 14-Jan-19 2:36am
Comments
PIEBALDconsult 13-Jan-19 23:04pm    
Any way you like.

Start by literally breaking it up - use var to get the "bits" apart, work from the left and process brackets as you meet them:
var inJoin = (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'))).ToArray();
return String.Join(".", inJoin);
var beforeArray = input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'));
var inJoin = beforeArray.ToArray();
return String.Join(".", inJoin);
var split = input.Split('.');
var beforeArray = split.Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'));
var inJoin = beforeArray.ToArray();
return String.Join(".", inJoin);
You can then use Intellisense to correct the types:
string[] split = input.Split('.');
var beforeArray = split.Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'));
string[] inJoin = beforeArray.ToArray();
return String.Join(".", inJoin);

The "bit inside the Select" is also pretty simple to break down:
private string BreakItDown(string x)
    {
    int intX = Int32.Parse(x);
    string converted = Convert.ToString(intX, 2);
    return converted.PadLeft(8, '0');

    }
private string myFunction(string input)
    {
    string[] split = input.Split('.');
    var beforeArray = split.Select(x => BreakItDown(x));
    string[] inJoin = beforeArray.ToArray();
    return String.Join(".", inJoin);
So, what it's it doing? converting a sequence of decimal numbers separated by dots to 8 digit binary numbers separated by dots
So "192.168.0.1" is converted to "11000000.10101000.00000000.00000001"

But it's actually more readable as a single line ... :laugh:
 
Share this answer
 
Comments
Maciej Los 14-Jan-19 5:29am    
5ed!
In addition to solution #1 by OriginalGriff, i would like to explain your problem in a bit different way. First of all, you have to understand what such of long line of code is doing to be able to split it into smaller pieces.
This:
return String.Join(".", (input.Split('.').Select(x => Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'))).ToArray());

actually means: join strings from a text splited by dots and converted into zero-one form.

There's one reduntant call: ToArray(), because string.Join() method accepts IEnumerable(Of T) as an input. See: String.Join Method (System) | Microsoft Docs[^]

How to write it line by line? Simple. See:
C#
string input = "192.168.0.1";
//split input into parts
var result = input.Split('.');
//returns an array os strings:
//192 
//168 
//0 
//1 

//convert each part
var result1 = result.Select(x =>Convert.ToString(Int32.Parse(x), 2).PadLeft(8, '0'));
//returns an IEnumerable<string>
//11000000 
//10101000 
//00000000 
//00000001 

//join strings
var result2= string.Join(".", result1);
//returns a string
//11000000.10101000.00000000.00000001


Finall note: C# is case sensitive. So, String is not the same as string. An explanation you'll find here: Strings - C# Programming Guide | Microsoft Docs[^]
 
Share this answer
 
solution 1 from OriginalGriff explains things very nicely
and solution 2 from Maciej Los also very good
and not to mention PIEBALDconsult comment "Any way you like" - nice :)

But possibly to help figure out how to get to solution 1 and 2.

One of the tricky parts I suppose in learning the language at hand is figuring out which of the words/bits belong to the language and which ones do not.

So in deciphering a one-liner, you will be required to do a lot of googling or possibly have a language reference at hand.

To simplify the one-liner, you could try adding carriage returns and indenting to help visualize better.

In the case of C#, separate by parenthesis, the comma and the dot.
C#
//expanded one-liner - something like this
return String.Join(
    ".", 
    (
        input.Split('.')
            .Select( x => 
                Convert.ToString(
                    Int32.Parse(x),
                    2
                )
                .PadLeft(8,'0')
            )
    )
    .ToArray()
);

Do searches with the program language of the one-liner - in this case C#
Let see what google search results we can get from above (if you know what they do already - no need to search):
return c# return statement - C# Reference | Microsoft Docs[^]
String c# String Class (System) | Microsoft Docs[^]
String.Join c# OR Join c# String.Join Method (System) | Microsoft Docs[^]
input.Split c# OR Split c# How to: Parse Strings Using String.Split (C# Guide) | Microsoft Docs[^]
.Select( x => c# c# - Possible purpose of LINQ select( x => x ) - Stack Overflow[^]
Convert.ToString c# Convert.ToString Method (System) | Microsoft Docs[^]
Int32.Parse c# Int32.Parse Method (System) | Microsoft Docs[^]
PadLeft c# String.PadLeft Method (System) | Microsoft Docs[^]
ToArray() c# List<T>.ToArray Method (System.Collections.Generic) | Microsoft Docs[^]

Add comments to the expanded one-liner - getting the information from the google searches.

C#
return String.Join(//return a string of Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member 
    ".", //using this separator
    (
        input.Split('.')//creates an array of substrings by splitting the input string based on one or more delimiters - using a separator as '.'
            .Select( x => //this is a tricky one - use linq select to parse the values somehow
                Convert.ToString(//Converts the specified value to its equivalent string representation
                    Int32.Parse(x),//Converts the string representation of a number to its 32-bit signed integer equivalent
                    2//Converts the value of a 32-bit signed integer to its equivalent string representation in a specified base
                )
                .PadLeft(8,'0')//returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length
            )
    )
    .ToArray()//An array containing copies of the elements of the List<T>
);

From this point - hopefully you will be able to figure out what parts can be broken down.
And expand to what you could get in Solution 1 and 2.


You may have noticed I didn't separate out all the words:
- String.Join
- input.Split
- Convert.ToString
- Int32.Parse
see what you get from searching them split up or not
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900