Ok so I have the following code that I looked up on the internet but for my project I am not allowed to use code and just throw it in if it works. I have to understand it and be able to give and explanation on the code and what it’s doing.
Convert.ToInt32("a").ToString("x");//ascii to hex
String.Join(String.Empty,
stringInput.Select(
c => Convert.ToString(
Convert.ToUInt32(c.ToString(), 16), 2).PadLeft(4, '0')));
Can you give me an explanation of these two lines please?
This code looks complex, because the author tried to pack as much functionality into one line as possible. (Were I in a grouchier mood I’d call this “showing off” and would probably complain if a junior tried to check this in.) However, no single part of that line of code is complex; just break it apart piece by piece and examine each bit.
For starters, that first line is just rubbish;
ToInt32("a")throws aFormatExceptionbecause you didn’t specify the base of 16, as:ToInt32("a", 16). If you fix it, though, it’s going to return10.ToString("x")which is"a". So ignore that line, it does nothing useful. (We can imagine the author meant to use something likeEncoding.UTF8.GetBytes()to return0x61, but they did not.)The second line, you break down each bit and see what it does:
This is pretty easy: it’s going to take an array of strings and join them together, using
String.Emptyas the separator (IOW, no separation.)Here’s we’re using LINQ to build up an
IEnumerableof strings; it’s going to loop through the characters in the string, one at a time, and execute the lambda expression on each one.Here’s where it gets messy, because even for me matching up those parenthesis by eye is a pain, but if you expand the nested function calls into temporaries, you get:
Each one of those “returned” values becomes the next element in the enumerable, which is returned by
Select, which is then joined.The end result here is that you start with a string of hexadecimal digits from 0 – F which, when read as a number, has some particular numeric value, and you end up with a string of binary digits 0 and 1 which, when read as a number, has the same numeric value. IOW, you are “converting” a string of hex digits into an “equivalet” string of binary digits.