tags:

views:

202

answers:

4

I have the following function to get an int from a high-byte and a low-byte:

public static int FromBytes(byte high, byte low)
{
    return high * (byte.MaxValue + 1) + low;
}

When I analyze the assembly with FxCop, I get the following critical warning:

CA2233: OperationsShouldNotOverflow
Arithmetic operations should not be done without first validating the operands to prevent overflow.

I can't see how this could possibly overflow, so I am just assuming FxCop is being overzealous.
Am I missing something? And what steps could be taken to correct what I have (or at least make the FxCop warning go away!)?

+5  A: 

It is doing them as byte calculations.

Try this

return (int)high * ((int)byte.MaxValue + 1) + (int)low;
Daniel A. White
+1 I was JUST about to answer with the same thing :)
Pwninstein
I was just about to write that! Nice and Fast. :)
Joshua
+1  A: 

Here's 2 ways that it finally stopped whining about CA2233 for me:

    public static int FromBytes(byte high, byte low)
    {
        int h = high;
        return h * (byte.MaxValue + 1) + low;
    }

    public static int FromBytes2(byte high, byte low)
    {
        unchecked
        {
            return high * (byte.MaxValue + 1) + low;
        }
    }

I think it might be a bug in the rule.

Sam Pearson
+2  A: 

Byte addition and mult results are ints. The max value here is 65535 which won't overflow an int. Just surpress the error.

byte a = 1;
byte b = 2;
object obj = a + b

obj has type int

Try this:

        byte high = 255;
        byte low = 255;
        checked
        {
            int b = high * (byte.MaxValue + 1) + low;   
        }

No problem.

or try this

csaam
+3  A: 

As Daniel A. White pointed out, you get the message because "(byte.MaxValue + 1)" overflows a byte.

But instead of casting and multiplying, I would simply shift the bits as done in the code below:

public static int FromBytes(byte high, byte low) {
    return high << 8 | low;
}

As a side effect, this code will probably perform better. I haven't checked the resulting IL or x86 to see if the compiler and/or the JITter are smart enough to optimize the original expression.

Alfred Myers