So after some searching it seems there isn't an exact match for this question that I could find. The closest is converting to a byte[]
in which the suggested answers do include a solution to this question, but the code is more complicated than needed for just a single byte.
If you simply have an 8 character string you can use the Convert.ToByte()
method:
string input = "00001111";
byte output = Convert.ToByte(input, 2);
It is worth noting that you should validate your input to ensure it is a valid 8 character string before trying to convert it. You can actually have less than 8 characters and it will assume leading zeros, as long as you have at least 1 character, but you cannot have more than 8. Characters must be either "0"
or "1"
.
Though I guess it depends on how reliable your input data will be to determine if it needs validation.