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,345
  • 10
  • 33
  • 34
Spartan
  • 35
  • 1
  • 7

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
  • 165,109
  • 17
  • 150
  • 199