Search code examples
c#bit-manipulationbitwise-operatorsbitwise-and

Help with bitwise operations


I want to doublecheck some of my logic against a 3rd party function that I am using and I'm not sure if I've got the bitwise logic figured out correctly or not. Can someone give me a range of values for the variable 'intValue' in each scenario that will cause each conditional to return true? thanks!

        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 {

        }

Solution

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

    Please note that all the intValue < 0 tests are completely redundant if the variable type is signed.