0

I have to execute a logical expression which is a string.

For example :

string s = "2 << 1"

How could I execute above "s" with the bitwise operator unknown at the time of executing.

EzLo
  • 13,780
  • 10
  • 33
  • 38
Spartan
  • 45
  • 1
  • 7
  • Do you always have two operands only? – Zhavat Feb 12 '19 at 07:27
  • 1
    Give us a code of what you are doing to solve this so far – Shahroozevsky Feb 12 '19 at 07:29
  • 5
    Split the string and use a `switch-case` or `if-else` for the operators? – jegtugado Feb 12 '19 at 07:29
  • Possible duplicate of [How can I evaluate a C# expression dynamically?](https://stackoverflow.com/questions/53844/how-can-i-evaluate-a-c-sharp-expression-dynamically) – John Wu Feb 12 '19 at 07:56
  • This question is a trap, unfortunately, because any answer that answers your direct question exactly is only going to lead to further questions in the comment, like "Yeah, ok, so `<<` is like that but what about `^`? What if `2` is a variable? What about nested expressions?". You must be much more explicitly but then the question is going to be too broad. Instead, focus on the most immediate problem and see if you can solve that, such as parsing it, otherwise you might want to start with a question about that instead. – Lasse V. Karlsen Feb 12 '19 at 08:27

2 Answers2

1

You may try the following:

string s = "2 << 1";
string operator_ = (new string(s.Where(c => !char.IsDigit(c)).ToArray())).Trim();
int operand1 = Convert.ToInt32(s.Substring(0, s.IndexOf(operator_)).Trim());
int operand2 = Convert.ToInt32(s.Substring(s.IndexOf(operator_) + operator_.Length).Trim());

int result = 0;
switch (operator_)
{
    case "<<":
         result = operand1 << operand2;
         break;
    case ">>":
         result = operand1 >> operand2;
         break;
}
Console.WriteLine(string.Format("{0} {1} {2} = {3}", operand1, operator_, operand2, result));
Zhavat
  • 214
  • 1
  • 6
0

You can try using regular expressions here in order to extract arguments and operation:

  using System.Text.RegularExpressions; 

  ...

  // Let's extract operations collection 
  // key: operation name, value: operation itself 
  Dictionary<string, Func<string, string, string>> operations =
    new Dictionary<string, Func<string, string, string>>() {
    { "<<", (x, y) => (long.Parse(x) << int.Parse(y)).ToString() },
    { ">>", (x, y) => (long.Parse(x) >> int.Parse(y)).ToString() }
  };

  string source = "2 << 1";

  var match = Regex.Match(source, @"(-?[0-9]+)\s*(\S+)\s(-?[0-9]+)");

  string result = match.Success
    ? operations.TryGetValue(match.Groups[2].Value, out var op) 
       ? op(match.Groups[1].Value, match.Groups[3].Value)
       : "Unknown Operation"  
    : "Syntax Error";

  // 4
  Console.Write(result);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215