2.15. Calculating Using Numbers in Bases Other Than Decimal

Problem

You want to perform mathematical operations with numbers formatted not in decimal, but in octal or hexadecimal. For example, you want to calculate web-safe colors in hexadecimal.

Solution

Prefix the number with a leading symbol, so PHP knows it isn’t in base 10. The following values are all equal:

0144  // base 8
 100  // base 10 
0x64  // base 16

Here’s how to count from decimal 1 to 15 using hexadecimal notation:

for ($i = 0x1; $i < 0x10; $i++) { print "$i\n"; }

Discussion

Even if you use hexadecimally formatted numbers in a for loop, by default, all numbers are printed in decimal. In other words, the code in the Solution doesn’t print out “..., 8, 9, a, b, ...”. To print in hexadecimal, use one of the methods listed in Recipe 2.15. Here’s an example:

for ($i = 0x1; $i < 0x10; $i++) { print dechex($i) . "\n"; }

For most calculations, it’s easier to use decimal. Sometimes, however, it’s more logical to switch to another base, for example, when using the 216 web-safe colors. Every web color code is of the form RRGGBB, where RR is the red color, GG is the green color, and BB is the blue color. Each color is actually a two-digit hexadecimal number between 0 and FF.

What makes web-safe colors special is that RR, GG, and BB each must be one of the following six numbers: 00, 33, 66, 99, CC, and FF (in decimal: 0, 51, 102, 153, 204, 255). So, 003366 is web-safe, but 112233 is not. Web-safe colors render without dithering on ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.