代码之家  ›  专栏  ›  技术社区  ›  Matthew King

为什么FxCop在这个C代码中警告溢出(CA2233)?

  •  6
  • Matthew King  · 技术社区  · 14 年前

    我有以下函数从高字节和低字节获取int:

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

    当我用FxCop分析程序集时,得到以下严重警告:

    CA2233:操作不应溢出
    未首先验证 防止溢出的操作数。


    我错过什么了吗?我们可以采取什么措施来纠正我的错误(或者至少让FxCop警告消失!)?

    4 回复  |  直到 12 年前
        1
  •  3
  •   Community datashaman    7 年前

    作为 Daniel A. White pointed out

    但是,我不需要强制转换和乘法,而是简单地按照下面的代码进行移位:

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

    作为副作用,此代码可能会执行得更好。我还没有检查生成的IL或x86,看看编译器和/或JITter是否足够聪明,可以优化原始表达式。

        2
  •  5
  •   Daniel A. White    14 年前

    它把它们当作字节计算。

    return (int)high * ((int)byte.MaxValue + 1) + (int)low;
    
        3
  •  4
  •   John Saunders Tony    14 年前

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

    试试这个:

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

    或者试试这个

        4
  •  3
  •   xofz    14 年前

        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;
            }
        }