简体   繁体   中英

Converting C assign/conditional statement to C#

I am translating some code from C to C#. I'm not sure how best to translate the following 2 lines:

if (tt = v >> 16)
{
    r = (t = tt >> 8) ? 24 + LT[t] : 16 + LT[tt];
}

tt, v, and t are ulongs (not really relevant to the problem). The problem is I don't think C# allows the assign/conditional operation in one statement.

In C#, one cannot implicitly convert from ulong to bool. The following line doesn't compile either:

if ((bool)(tt = v >> 16))

Here is the one for your if statement.

(tt = v >> 16) != 0

You cant easily cast an int to a bool .

This is a direct conversion:

tt = v >> 16;
if (tt != 0) {
    t = tt >> 8;
    r = (t != 0) ? 24 + LT[t] : 16 + LT[tt];
}

Generally speaking, terse C code doesn't look good when converted to C#. I suggest making it a little bit more verbose to make life easier in the future. (Call me biased, but it takes a lot more to frighten people used to C than those using newer languages).

Try this:

tt = v >> 16;
if (tt != 0)

This shoud simply work:

tt = v >> 16;
if (tt != 0)
{
    t = tt >> 8;
    r = (t != 0) ? 24 + LT[t] : 16 + LT[tt];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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