@anon951759: OH GOD NO!
MAGIC NUMBERS ARE A CODE SMELL. A REALLY BAD ONE!
Okey… so the solution:
We want to get rid of all those magic numbers -> What do they actually mean? Yep. They’re unique for every color you can get.
They look like this, in binary:
RRRR RRRR GGGG GGGG BBBB BBBB AAAA AAAA 0000 0000 0000 0000 0000 0000 0000 0000
(or probably the A’s are the first 8 bit, dunno so well right now turns out it’s ARGB, not RGBA, see answer below)
R = Red
G = Green
B = Blue
A = Alpha
So the first 8 bits tell you about the red color amount of your pixel, the next 8 bits the green amount, etc.
And since they’re 8 bytes, they’re actually values from 0 to 255, where the higher the number is, the higher the amount of the color. In the end everything is packed into 32 bytes, so we have 4 numbers, each composed form 8 bits, which fit into 32 bits in total.
So the numbers are only a pretty strange way of visualizing that 4-component “number”. What you do there is simply interpreting all components together as one number, which is simply ‘wrong’ (imagine it to be like a hashCode)…
In hexadecimal 4 bits are one digit.
HEX -> BINARY -> DECIMAL 0 -> 0000 -> 0 1 -> 0001 -> 1 2 -> 0010 -> 2 3 -> 0011 -> 3 A -> 0110 -> 10 F -> 1111 -> 15
It won’t go higher than F, since we can only fit 4 binary 1’s into our 4 bits.
And in the end we can show our color as hexadecimal value. To make a hexadecimal literal in Java, you need to prepend your number with “0x”.
RRGGBBAA 0x00FF00FF
That’s a number with no red and blue but with a full green and alpha channel.
Now we know where those magic numbers come from, how can we make our magic numbers disappear from the code?
Well, we could use literals like [icode]0x09F1ACFF[/icode] in our code, but that’s still magic numbers, we need to name them:
public static final int COL_GRASS = 0x00FF00FF; // Pure, visible green
public static final int COL_STONE = 0x333333FF; // Dark, visible gray
[...]
switch (color) {
case COL_GRASS: ...
case COL_STONE: ...
}
Now where can we get those [icode]0x00FF00FF[/icode] numbers from? Easy, here’s a screenshot from the Gimp color picker:
See the box “HTML notation”? Append a “FF” and everything will be fine
In that screenshot you can also see, what the color “0x00FF00
” looks like: Green