Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata