从给定字符串转换回 byte/sbyte

A convert back from the given string into byte/sbyte

我有一个函数可以像这样形成一个字符串

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;
   }
}

这样,如果我输入一个 sbyte(9),那么字符串结果将是“10010000”,所以问题来了,我怎样才能将字符串“10010000”转换回给定的 sbyte?

您可能知道二进制是如何工作的。他们是2^0+2^1+2^2+2^3+...。所以当字符串为10010000时,你可以直接将结果设置为2^0+2^3。我认为您的输出二进制字符串的顺序相反。字符串应该是00001001,高位在前,低位在后。因为第一位是 1 所以结果加 2^0,第四个元素是 1 所以结果应该加 2^3。然后你就得到了结果。

string str = "10010000";
str = (str.TrimEnd('0', '[=10=]'));
sbyte s = Convert.ToSByte(str, 2);

首先从字符串中删除所有尾随零,然后转换为基数为 2 的 sbyte。它会返回 9。