| Calculating a Contrasting Color Code | |
| Part 4: The First Bug | |
|
Here's where I ran into the first interesting bug. Those of you who are really paying attention might have noticed that Microsoft, in their infinite wisdom, made the Foreground/Background code "Blue-Green-Red," not "Red-Green-Blue" like HTML and most everything else. This accounts for the requirement to count down rather than up in the second loop in the program above: For J = 2 To 0 Step -1 In the VB 6 Help, it states, "you can specify a color as a hexadecimal number using this syntax: &HBBGGRR& The BB specifies the amount of blue, GG the amount of green, and RR the amount of red.") Given this interesting Microsoft inconsistency in the representation of color in VB, you might be able to use the code in this article to convert from one Microsoft version of color coding to another some day. Getting back to the main topic, the only way I know to really understand the logical calculation is to understand it in binary. The hex value, 7CE0F9 is equal to the following number in binary (spaces are added for legibility): Let's apply the formula to this. Note that this leaves the Red and Blue values the same, but reverses the Green. Reversing the bits of a binary number is what Xor is usually used for. This gives us only the Green part of the previous result. Everything else is zero. The And operation is usually used to extract bits from a larger number. This gives us the Blue and Red part of the color code and forces the Green part to zero. In the next step, Or is used to combine the inverse of the Green part along with ONLY the original Red and Blue part. Notice now that we have identically the same Blue and Red values, but the Green value has been exactly reversed. If all we wanted to do was to reverse the Green, this would be great! Unfortunately, we want to reverse all three. But wait! The number we need to do that is one of the intermediate results in the formula. That, in fact is what the And Result (First Part) was. If we apply the formula just down to that point for all three colors, we get (repeating for the other two colors): Blue Red We can combine them back into a single number by simply adding them. |
|
