2

我想根据我正在使用的第 3 方函数仔细检查我的一些逻辑,但我不确定我是否正确计算了按位逻辑。有人可以在每种情况下给我一个变量“intValue”的值范围,这会导致每个条件返回真吗?谢谢!

        if ((intValue < 0 && ((intValue & 0xFFFFFF80) == 0xFFFFFF80)) ||
            (intValue & 0x0000007F) == intValue) {

        }
        else if ((intValue < 0 && ((intValue & 0xFFFF8000) == 0xFFFF8000)) ||
            (intValue & 0x00007FFF) == intValue) {

        }
        else if ((intValue < 0 && ((intValue & 0xFF800000) == 0xFF800000)) ||
            (intValue & 0x007FFFFF) == intValue) {

        }
        else {

        }
4

2 回答 2

2
if (intValue == (SByte)intValue) {
     // matches -128...127, i.e. values that fit in one byte
}
else if (intValue == (Int16)intValue) {
     // matches -32768..32767, values that fit in two bytes
}
else if (intValue == ((intValue << 8) >> 8)) {
     // matches -2**23..(2**23-1), values that fit in three bytes
}
else {
     // matches -2**31..(2**31-1), values that need four bytes
}

请注意,intValue < 0如果变量类型已签名,则所有测试都是完全多余的。

于 2011-07-08T23:58:41.143 回答
-1

这里有一个提示:

int intValue = int.Parse("FFFFFF80", System.Globalization.NumberStyles.HexNumber);

看:

C#将整数转换为十六进制并再次返回

于 2011-07-08T23:40:25.530 回答