48

I have a binary string, entered by the user, which I need to convert to an integer.

At first, I naively used this simple line:

Convert.ToInt32("11011",2);

Unfortunately, this throws an exception if the user enters the integer directly.

Convert.ToInt32("123",2); // throws Exception

How can I make sure that the string entered by the user actually is a binary string?

  • try..catch
  • Int32.TryParse

Thanks

3
  • 1
    How does the user enter the string? If it's a form, couldn't you limit it to accept only '0' and '1'?
    – outis
    Aug 13, 2009 at 12:19
  • 3
    Why is try - catch "ugly"?
    – RaYell
    Aug 13, 2009 at 12:25
  • You are probably right, it is not that ugly. I actually went with it now because Hex value are suddenly possible aswell. So some simple try - catches are just the simplest and easiest solution. Thanks everybody.
    – eric
    Aug 14, 2009 at 5:52

2 Answers 2

35

You could use a Regex to check that it is "^[01]+$" (or better, "^[01]{1,32}$"), and then use Convert?

of course, exceptions are unlikely to be a huge problem anyway! Inelegant? maybe. But they work.

Example (formatted for vertical space):

static readonly Regex binary = new Regex("^[01]{1,32}$", RegexOptions.Compiled);
static void Main() {
    Test("");
    Test("01101");
    Test("123");
    Test("0110101101010110101010101010001010100011010100101010");
}
static void Test(string s) {
    if (binary.IsMatch(s)) {
        Console.WriteLine(Convert.ToInt32(s, 2));
    } else {
        Console.WriteLine("invalid: " + s);
    }
}
5
  • 1
    This doesn't correctly handle conversion of Convert.ToString((long)Int32.MaxValue + 1, 2). This should be rejected but is incorrectly converted to Int32.MinValue.
    – Ben Lings
    Aug 13, 2009 at 12:32
  • 2
    Why should that be rejected? It is a valid 32-bit binary value. If you choose to interpret it as int32 then sure: anything with the msb set is going to be negative... and? Aug 13, 2009 at 12:38
  • Thanks great solution. I actually went with it. But the requirements changed some what so I decided try - catch is the simplest and cleanest solution
    – eric
    Aug 14, 2009 at 5:54
  • I don't have much Regex experience, does this check that there are 1-32 characters and these have to be either 0 or 1? What's the best way to do a similar check for valid octal strings? I wish that .NET would have a int.TryParse where you check for Binary and Octal instead of just Decimal and Hex
    – R1PFake
    May 31, 2018 at 11:53
  • @R1PFake yes, ^...$ tests the start/end of the string (so: nothing else); [01] means "0 or 1", and {1,32} means "between 1 and 32 times, inclusive" May 31, 2018 at 12:03
4

Thanks for the great and incredibly fast answer!

Unfortunately, my requirements changed. Now the user can pretty much enter any format. Binary, Decimal, Hex. So I decided try - catch just provides the simplest and cleanest solution.

So just for good measure I am posting the code I am using now. I think it is pretty clear and even somewhat elegant, or so I think^^.

switch (format)
{
    case VariableFormat.Binary:
        try
        {
            result = Convert.ToInt64(value, 2)
        }
        catch
        {
            // error handling
        }
        break;
    case VariableFormat.Decimal:
        try
        {
            result = Convert.ToInt64(value, 10)
        }
        catch
        {
            // error handling
        }
        break;
    case VariableFormat.Hexadecimal:
        try
        {
            result = Convert.ToInt64(value, 16)
        }
        catch
        {
            // error handling
        }
        break;
}

So thanks for encouraging me to use try - catch, I think it really improved the readibility of my code.

Thanks

2
  • 1
    What, you don't like octal? Seriously though, what if someone enters '11' and meant it in base 10? Standard solution would be to use a prefix ('0b', '', '0x'), but that may not fit your requirements.
    – outis
    Aug 16, 2009 at 7:13
  • 1
    Yeah no octal^^. The user actually has to choose in combobox which format she wants to use. I thought about your solution too, but it seemed easier with a combobox. Thanks so great input.
    – eric
    Aug 17, 2009 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.