-1

I have a function which form a string like this

public static string formString(sbyte myByte)
{
   try
   {
      var str = string.Empty;
      for (int i = 0; i <= 7; i++)
      {
         if(( (1<<i) & myByte ) == 0)
         {
            str = str + "0";
         }
         else
         {
            str = str + "1";
         }
      }
      return str;
   }
   catch (System.Exception ex)
   {
      return null;
   }
}

In this way, if I put a sbyte like(9), then the string result will be "10010000" , so here's the question , how can I just convert string "10010000" back to the given sbyte?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Cagaya Coper
  • 75
  • 1
  • 12

2 Answers2

1

You probably know how binary works. They are 2^0+2^1+2^2+2^3+.... So when the string is 10010000, you can just set the result as 2^0+2^3. I think your output binary string are in reverse order. The string should be 00001001, you should put the high bit in front of the string and low bit at the back of string. Because the first bit is 1 so the result add 2^0, and the forth element is 1 so the result should add by 2^3. And then you get the result.

1
string str = "10010000";
str = (str.TrimEnd('0', '\0'));
sbyte s = Convert.ToSByte(str, 2);

First remove all the trailing zeros from string and then convert to sbyte with base 2. It will give you back 9.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197