现在要把一个int数(32位)的4个字节倒置,有下面两种写法。不知道为什么,第一种写法是正确的,第二种写法确报错

        public static int reverseInt(int i)
{
    int t = (((i & -0x01000000) >> 24) & 0xff) 
                | ((i & 0xff0000) >> 8) 
                | ((i & 0xff00) << 8) 
                | ((i & 0xff) << 24); return t;
}        public static int reverseInt2(int i)
        {
            int t = (((i & 0xff000000) >> 24) & 0xff)
                | ((i & 0xff0000) >> 8)
                | ((i & 0xff00) << 8)
                | ((i & 0xff) << 24);            return t;
        }我是在VS2005里用C#写的,报的错误如下:
Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
请高手指教!!

解决方案 »

  1.   

    因为0xff000000不是int型,它溢出了(-2,147,483,648 到 2,147,483,647)。
    它可以是uint类型也可以是long类型。
    不过你可以这么写
                unchecked
                {
                    int t = (((i & (int)0xff000000) >> 24) & 0xff)
                         | ((i & 0xff0000) >> 8)
                         | ((i & 0xff00) << 8)
                         | ((i & 0xff) << 24);
                }