Bases and Bits

Number Bases and Bit Manipulation

Literals come in four bases: 202, 0xCA, 0b1100_1010 and 0o312 (0o is PHP 8.1). decbin(), decoct() and dechex() return strings; bindec(), octdec() and hexdec() parse them; base_convert() handles bases 2 to 36; intval($s, 0) detects 0x, 0b or a leading 0; and sprintf() offers %b, %o and %X.

Base conversion, and packing a color with shifts and masks (bases.php)PHP
<?php
echo decbin(202), ' ', decoct(202), ' ', dechex(202), ' ', base_convert('ca', 16, 36), ' | ',
    bindec('11001010'), ' ', hexdec('CA'), ' ', intval('0312', 0), ' ', intval('0o312', 0),
    ' ', sprintf('%08b %X', 5, 255), ' | ', base_convert('ffffffffffffffff', 16, 10), "\n";
// Pack an RGB color into one int, then unpack it with shifts and masks.
$packRgb = fn(int $r, int $g, int $b): int => ($r << 16) | ($g << 8) | $b;
$unpack  = fn(int $c): array => [($c >> 16) & 0xFF, ($c >> 8) & 0xFF, $c & 0xFF];
$teal = $packRgb(0, 128, 128);
$flags = 0b1011_0010;
printf("#%06X %s | bit 4: %d, bits set: %d | %d %d %d\n", $teal, json_encode($unpack($teal)),
    ($flags >> 4) & 1, substr_count(decbin($flags), '1'), -16 >> 2, 1 << 63, 1 << 64);
Output
11001010 312 ca 5m | 202 202 202 0 00000101 FF | 18446744073709552046
#008080 [0,128,128] | bit 4: 1, bits set: 4 | -4 -9223372036854775808 0

intval() does not know the 0o prefix, so it returns 0. base_convert() works through a float, so 2^64 - 1 (18446744073709551615) comes back wrong; use BCMath or GMP beyond PHP_INT_MAX. Shifts are 64-bit and signed: >> copies the sign bit, 1 << 63 is PHP_INT_MIN, a shift of 64 gives 0, and a negative shift throws ArithmeticError. GD packs colors this way (GD Images).