Search code examples
objective-ctypestype-conversionbitwise-operatorsinteger-promotion

How does Objective-C handle bitmasking when arguments are not the same size?


When coding in Objective-C, what should the compiler do when it bitwise ANDs (or performs other bitwise operations) on two variables of different size?

For example, lets say I have some variables as follows:

unsigned long longVar   = 0xDEADF00D;
unsigned short shortVar = 0xBEEF;

If I bitmask the long with a short-sized mask, clearly we'll just select out the bits of interest:

maskOut = longVar & 0xFFFF;    // this == 0xFOOD

If I bitmask the short with a long,

maskOut = shortVar & 0xFFFFFFF0;

it seems like this should pad the top with zeros,

0x0000BEEF & 0xFFFFFFF0  // == 0xBEE0

but is it guaranteed to do this, or could it be anything which happens to be in memory that is sitting there, more like:

0x????BEEF & 0xFFFFFFF0  // == 0x????BEE0

Clearly, the latter could produce unspecified effects, and is undesirable.

I found code of this nature in a program I was cleaning up, and I simply increased the size of the type to be safe, but I wanted to know if it was really necessary.


Solution

  • Objective-C is an extension of C. The behaviour is therefore exactly the same as for C. Google for "C standard draft" and download a copy of a draft for the latest C standard (the drafts are free, the final standard costs about $60, but the draft is just fine unless you write compilers for a living). Then you look for "integer promotions".

    In general, as long as your values are all unsigned, operands of different sizes are extended to the size of the operand with larger size by filling with zeroes. If you mix signed and unsigned values, things get complicated and can cause headaches.