1

I want to convert string that have value like "00001111" to byte

I tried this code for convert from byte to string:

byte b = 255;
string s = Convert.ToString(b, 2).PadLeft(8, '0');
Console.WriteLine(s);

This code works fine, but I need the opposite to convert from binary string back to a byte.

musefan
  • 45,726
  • 20
  • 123
  • 171

2 Answers2

1

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.

musefan
  • 45,726
  • 20
  • 123
  • 171
1

Even if the the standard library didn't have a built-in function, you could write one pretty easily:

var s = "00001111";
var n = 0d;

for(var i = 0; i < s.Length; i++)
{   
    var d = s[s.Length - 1 - i] == '0' ? 0 : 1;     
    n += (d * Math.Pow(2, i));
}

var b = (byte)(((int)n) & 0xFF);

To validate the input (which you will probably want to do in any case):

s.Length <= 8 && s.All(c => c == '0' || c == '1');
Rodrick Chapman
  • 5,247
  • 1
  • 27
  • 32
  • 2
    Does it not defeat the point of writing your own function if you end up using `Convert.ToByte()` as part of it? You would also probably want to validate null and empty strings too – musefan Aug 23 '17 at 14:25