One thing I’ve never really understood is why in many libraries, constants are defined like this:
public static final int DM_FILL_BACKGROUND = 0x2;
public static final int DM_FILL_PREVIOUS = 0x3;
public static final int TRANSPARENCY_MASK = 1 << 1;
public static final int TRANSPARENCY_PIXEL = 1 << 2;
What’s up with the 0x and << stuff? Why aren’t people just using ordinary integer values?
The bit shifting of
1is usually for situations where you have non-exclusive values that you want to store.For example, say you want to be able to draw lines on any side of a box. You define:
Then you can combine them for multiple sides:
The fact that they’re using totally different bits means that they’re independent of each other. By
ORing them you get1 | 2 | 4which is equal to7and you can detect each individual bit with other boolean operations (see here and here for an explanation of these).If they were defined as 1, 2, 3 and 4 then you’d probably either have to make one call for each side or you’d have to pass four different parameters, one per side. Otherwise you couldn’t tell the difference between
LEFT and RIGHT(1 + 2 = 3) andTOP(3), since both of them would be the same value (with a simple addition operation).The
0xstuff is just hexadecimal numbers which are easier to see as binary bitmasks (each hexadecimal digit corresponds exactly with four binary digits. You’ll tend to see patterns like0x01,0x02,0x04,0x08,0x10,0x20and so on, since they’re the equivalent of a single1bit moving towards the most significant bit position – those values are equivalent to binary00000001,00000010,00000100,00001000,00010000,00100000and so on.