Вопрос

I have a DataColumn implementation to evaluate expressions at runtime. For my surprise, DataColumn operations seens not to support bitwise operators.

In need to check for individual bits set or groups of bits set. Examples:

(Value & 0x0002) to check for the 2nd bit set. Shall return true (1).

((Value & 0x000F) == 0x03) to check if the first 4 bits of Value has a value of 3.

Is there any way to support these bitwise operations using DataColumn class ?

Is there an alternative to DataColumn that does support bitwise operations ?

Suggestions on how to do it using common math operators ?

[EDIT - Complete function code]

public static bool EvaluateExpression(string expression, object value, out object returnValue, out string errorMessge)
{
    try
    {
        errorMessge = String.Empty;

        ///
        /// First substitute the references of object with its value
        /// 
        string evalExpression = expression.Replace("[this]", Convert.ToString(value));

        ///
        /// Now evaluate the expression
        /// 
        DataTable loDataTable = new DataTable();

        double dummyResult;
        DataColumn loDataColumn;

        if (Double.TryParse(evalExpression, out dummyResult))
            loDataColumn = new DataColumn("Eval", typeof(double), evalExpression);
        else
            loDataColumn = new DataColumn("Eval", typeof(string), evalExpression);

        loDataTable.Columns.Add(loDataColumn);
        loDataTable.Rows.Add(0);

        returnValue = (object) loDataTable.Rows[0]["Eval"];

        return true;
    }
    catch (Exception e)
    {
        errorMessge = e.Message.ToString();
        returnValue = 0;
        return false;
    }
}

Calling the function in a example...

.
.
.
.
object val = (object) 12538;

string errorMsg = String.Empty;

object result;

string expr = "[this] & 0x02";

if (!EvaluateExpression (expr, val, result, errorMsg))
{
    Console.WriteLine("Error on expression. Error = " + errorMsg);
}
else
{
    Console.WriteLine("The resulting valur is " + val.ToString();
}
Это было полезно?

Решение 2

As per @sdf, they do not support bitwise operations, but some bitwise operations can be simulated with the operators available. For example:

  • [this] & 0x02 is equivalent to IIF(Convert([this]/2, 'System.Int32')%2 = 0, 0, 2)
  • [this] | 0x02 is equivalent to IIF(Convert([this]/2, 'System.Int32')%2 = 0, [this] + 2, [this])
  • [this] >> 2 is equivalent to Convert([this]/4, 'System.Int32')
  • [this] << 2 is equivalent to Convert([this]*4, 'System.Int32')

Другие советы

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top