0

Can you please explain me this code -

return string.Join(string.Empty, checkSum.Select(x => Convert.ToString(x, 2).PadLeft(8, '0')).

checkSum will have binary value like 10101010100011.

Checked in google but didn't find clear explanation.

burnsi
  • 6,194
  • 13
  • 17
  • 27
Syed
  • 1
  • 1
  • 1
    It is a lot more obvious when you set checkSum to 3. Convert.ToString() then generates "11", PadLeft() turns that into "00000011" so it has enough digits to represent the bits in a byte. – Hans Passant Jan 27 '23 at 12:00
  • It's hard to explain the `.` at the end. – Palle Due Jan 27 '23 at 12:22
  • I am confused by this code. What is the type of `checkSum` variable? String? One closing parenthesses is missing. If I put it at the end and set `checkSum` to "3" I get `00110011`. Makes no sense. – Dialecticus Jan 27 '23 at 12:23
  • Assuming `chackSum` is string, this code converts every character to ASCII binary value, and then concatenates those binary values. What's the point? – Dialecticus Jan 27 '23 at 12:30
  • `PadLeft(8, '0')` - we want **at least** `8` characters, if we don't have enough, add `0` from the left – Dmitry Bychenko Jan 27 '23 at 12:39

1 Answers1

2

You can find the PadLeft documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.string.padleft

It works by "resizing" the string to a certain length by prepending spaces to make it the desired length. That same page includes this example:

string str = "BBQ and Slaw";
Console.WriteLine(str.PadLeft(15));  // Displays "   BBQ and Slaw".
Console.WriteLine(str.PadLeft(5));   // Displays "BBQ and Slaw".

Your particular code works such that an array of numbers checkSum is mapped via Select to all be binary numerals not integers (ToString(x, 2)) and the binary form is padded to always be 8 characters but not padded by spaces but by zeroes.

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125