Assuming that your data is in a form where each string of 8 characters contains only the characters '0' and '1' ... and that expresses the string representation of the 8
bits in a byte ...
List<int> Pow2 = new List<int> { 128, 64, 32, 16, 8, 4, 2, 1 };
private byte? StringToByte(string byteString)
{
if (byteString.Length != 8) return null;
foreach(char c in byteString) { if (c != '0' && c != '1') return null;}
int byteResult = 0;
for (int i = 0; i < byteString.Length; i++)
{
byteResult +=
(byteString[i] == '0')
? 0
: Pow2[i];
}
return Convert.ToByte(byteResult);
}
Testing:
byte? byte1 = StringToByte("00000000");
byte? byte2 = StringToByte("00000001");
byte? byte3 = StringToByte("01000001");
byte? byte4 = StringToByte("10000000");
byte? byte5 = StringToByte("11111111");
byte? byte6 = StringToByte("1111111111");
byte? byte7 = StringToByte("111");
byte? byte8 = StringToByte("1311111111");
byte? byte9 = StringToByte("1311Y11111");
The use of the nullable Byte return Type essentially defers checking for an error to the code calling the method: if you'd rather throw an error in the method, then change the return Type, and change the code.