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
The decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n): decimal = d0×20 + d1×21 + d2×22 + ...
In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.
Convert a Binary String to Int in Java Using Integer. parseInt() The first method is Integer. parseInt() that parses the given string into an int .
To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .
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); } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With