2

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 {

        }
snappymcsnap
  • 1,780
  • 2
  • 25
  • 47

2 Answers2

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
}

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

Ben Voigt
  • 260,885
  • 36
  • 380
  • 671
-1

Here's a hint:

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

See:

C# convert integer to hex and back again

Community
  • 1
  • 1
Chuck Savage
  • 11,274
  • 6
  • 46
  • 65