0

I hope and you can help me please, I have a label that shows a value in binary.

Example: "1000010101", this data, I'm reading it with an inverted for. That is, starting from right to left, the binary number is dynamic, so it will not always be the same.

Until now this is my idea, but it does not give me any value

for (int i = lbl_conversion.Text.Length; i > 0; i--)
    {
        if (st[i] == 1)
        {
            MessageBox("1");
        }
        else
        {
            MessageBox("0");
        }

    }

What I would like is to read character by character from left to right and know if it is "1" or "0" and then make a comparison, could someone support me to get that result?

Thank you.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Ric_hc
  • 279
  • 2
  • 13

3 Answers3

2

Since strings are zero based, correct for loop will be

   // Note "- 1" and ">=" 
   for (int i = lbl_conversion.Text.Length - 1; i >= 0; --i)
       if (st[i] == '1') //DONE: comparing with character, not integer
       {
           MessageBox("1");
       }
       else
       {
           MessageBox("0");
       }

Or you can just Reverse the string (with a help of Linq):

   // Let's read each character in reversed order
   foreach (char c in lbl_conversion.Text.Reverse())
       MessageBox(c.ToString()); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

just one more (similar to prev posted)

string s="10111011";
s.Reverse().ToList().ForEach(ch=>Console.WriteLine(ch=='1'?"A":"0"));
AndrewF
  • 33
  • 3
0

When you need read the string to right to left, typically you know the number of character to have to read.

I have this function.

 private string GetValue(string strValor, int lenght)
    {
        if (strValor.Length > lenght)
            return strValor.Substring(strValor.Length - lenght, lenght);
        return strValor;
    }
  • strValor: String to read.
  • lenght: Number of character to read.

Example: GetValue("R6C5736423792", 10); return "5736423792"

A. Senna
  • 131
  • 1
  • 6