简体   繁体   English

如何在Delphi中评估包含二进制公式的字符串?

[英]How can I evaluate a string containing a binary formula in Delphi?

In Delphi XE I have a routine that breaks down some complicated formulas to a binary formula result like this: 在Delphi XE中,我有一个例程,可以将一些复杂的公式分解为二进制公式,如下所示:

(1&((1|0)|1)&1) (1((1 | 0)| 1)&1)

Since my application is on SQL Server I can easily do a SELECT (1&((1|0)|1)&1) As Result and SQL Server will evaluate the logic to give me a 1 or 0 result. 由于我的应用程序在SQL Server上,因此我可以轻松地执行SELECT(1&(((1 | 0)| 1)&1)作为结果,SQL Server会评估逻辑以得出1或0的结果。

I cannot seem to find a native Delphi way of taking a string representation of a binary formula and evaluating it. 我似乎找不到原生的Delphi方式来获取二进制公式的字符串表示形式并对其进行评估。

I looked into the Live Bindings Evaluators added to XE but any attempt at the and/or operators throws parser errors so I believe that to be more of a mathematical process. 我调查了添加到XE的“实时绑定评估器”,但是对and和/或运算符的任何尝试均会引发解析器错误,因此我认为这更多的是数学过程。

I also looked at a few parsers but none really seemed to jump out at me. 我也看了几个解析器,但似乎没有一个真的跳出来。

So how can I do something similar to: 那么我该如何做类似的事情:

iSomeInt := Evaluate('(1&((1|0)|1)&1)'); iSomeInt:= Evaluate('(1&(((1 | 0)| 1)&1)');

BTW.. I can totally rework the formula and use and/or instead of &|.. that was just to make it work with SQL Server. 顺便说一句..我完全可以重新设计公式并使用和/或代替&| ..,这只是为了使其与SQL Server一起使用。

The problem isn't that it's "a mathematical process" so much as that the LiveBindings parser expects your mathematical process to be expressed with Pascal operators, but & and | 问题不在于它是一个“数学过程”,而是LiveBindings解析器希望您的数学过程用Pascal运算符表示,而是&和| |。 are C operators. 是C运算符。

Try something like this, assuming you have a function called LiveBindingsEval which evaluates a string with the LiveBindings parser: 假设您有一个名为LiveBindingsEval的函数,可以使用LiveBindings解析器对字符串求值:

function PreprocessExpression(const expr: string): string;
begin
   result := StringReplace(expr, '|', ' or ', [rfReplaceAll]);
   result := StringReplace(result, '&', ' and ', [rfReplaceAll]);
end;

iSomeInt := LiveBindingsEval(PreprocessExpression('(1&((1|0)|1)&1)'));

You may need to improve on this a little, but this should be enough to get you started on the right path... 您可能需要对此进行一些改进,但这足以使您开始正确的道路...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM