Cagaya Coper Cagaya Coper - 1 month ago 7
C# Question

A convert back from the given string into byte/sbyte

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?

thanks

Answer
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.