c# - 帮助进行位运算

标签 c# bit-manipulation bitwise-operators bitwise-and

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

        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 {

        }

最佳答案

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如果变量类型是有符号的,测试是完全多余的。

关于c# - 帮助进行位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6630886/

相关文章:

go - 对于常量表达式和其他表达式,Go编译器的评估是否有所不同

c - 为什么将整数左移 24 位会产生错误的结果?

c# - 计算 char 的按位反转

C# API 创建网页缩略图

c# - 将参数传递给 WebClient.DownloadFileCompleted 事件

math - 有没有人试图打破更小一点?

c++ - 轮类作业

c - 为什么 ~0 >> 1 不移动位?

C# - 永久删除文件

c# - 在 RTF 中提取嵌入的图像对象