


Working with Binary, Octal, and Hexadecimal Number Systems in PHP
Aug 01, 2025 am 07:38 AMPHP supports binary, octal, and hexadecimal number systems using specific prefixes and conversion functions. 1. Binary numbers are prefixed with 0b (e.g., 0b1010 = 10 in decimal). 2. Octal numbers use 0 or 0o (e.g., 012 or 0o12 = 10 in decimal). 3. Hexadecimal numbers use 0x (e.g., 0xA = 10 in decimal). 4. Use decbin() and bindec() to convert between decimal and binary. 5. Use decoct() and octdec() for decimal-octal conversions. 6. Use dechex() and hexdec() for decimal-hexadecimal conversions. 7. Use intval($string, $base) to safely convert strings from any base to decimal. 8. Be cautious with leading zeros in older PHP versions, as they indicate octal interpretation. 9. These systems are used in file permissions (octal), bitwise operations (binary), and color codes (hexadecimal). 10. Always validate input when handling string-based numbers to avoid unexpected behavior, as PHP’s conversion functions may ignore invalid characters or apply automatic interpretation. Proper use of prefixes and functions ensures accurate cross-base number handling in PHP.
When working with different number systems in PHP—like binary, octal, and hexadecimal—it’s important to understand how PHP interprets and converts these values. While PHP primarily works with decimal (base-10) numbers, it provides built-in functions and syntax to handle binary (base-2), octal (base-8), and hexadecimal (base-16) seamlessly.

How PHP Recognizes Different Number Bases
PHP allows you to define integers using different bases directly in code using specific prefixes:
-
Binary (base-2): Prefix with
0b
Example:0b1010
→ 10 in decimal -
Octal (base-8): Prefix with
0
or0o
(since PHP 8.1)
Example:012
or0o12
→ 10 in decimal -
Hexadecimal (base-16): Prefix with
0x
Example:0xA
→ 10 in decimal
echo 0b1010; // Outputs: 10 echo 012; // Outputs: 10 echo 0o12; // Outputs: 10 (PHP 8.1 ) echo 0xA; // Outputs: 10
?? Note: Older versions of PHP interpret a leading zero (e.g.,
012
) as octal. Be careful when parsing strings or user input with leading zeros.
Converting Numbers Between Bases
PHP provides several built-in functions to convert numbers between different bases.
1. decbin()
and bindec()
– Decimal to Binary and Back
decbin($number)
converts a decimal number to binary (returns a string).bindec($binaryString)
converts a binary string back to decimal.
echo decbin(10); // Outputs: 1010 echo bindec('1010'); // Outputs: 10
Note:
bindec()
ignores leading zeros and is case-insensitive for input.
2. decoct()
and octdec()
– Decimal to Octal and Back
decoct($number)
converts decimal to octal.octdec($octalString)
converts octal string to decimal.
echo decoct(10); // Outputs: 12 echo octdec('12'); // Outputs: 10
3. dechex()
and hexdec()
– Decimal to Hexadecimal and Back
dechex($number)
converts decimal to hexadecimal (lowercase).hexdec($hexString)
converts hex string to decimal (ignores case and0x
prefix).
echo dechex(255); // Outputs: ff echo hexdec('FF'); // Outputs: 255 echo hexdec('0xFF'); // Also valid → 255
Note:
hexdec()
is forgiving—it skips non-hex characters like0x
, but be cautious with malformed input.
Practical Use Cases
These number systems are commonly used in:
- Permissions and file modes (octal):
chmod('file.txt', 0644); // 0644 is octal
- Bitwise operations (binary):
$flags = 0b1010 | 0b0110; // Bitwise OR
- Color codes and memory addresses (hexadecimal):
$color = 0xFF5733; // Represents a color in RGB
Handling String Inputs and Edge Cases
When dealing with user input or strings, always validate and sanitize:
Use
intval($string, $base)
to convert a string to an integer in a given base:intval('1010', 2); // Binary string → 10 intval('12', 8); // Octal string → 10 intval('A', 16); // Hex string → 10
This is safer than relying on automatic type conversion.
- Binary strings must contain only
0
and1
. - Invalid octal digits (like
8
or9
) cause silent truncation or errors depending on context. - Hex strings can include
a-f
orA-F
.
Also, be aware:
Summary of Key Functions
Conversion | Function |
---|---|
Decimal → Binary | decbin() |
Binary → Decimal | bindec() |
Decimal → Octal | decoct() |
Octal → Decimal | octdec() |
Decimal → Hex | dechex() |
Hex → Decimal | hexdec() |
Any base → Decimal | intval($str, $base) |
Basically, PHP makes it straightforward to work across number systems—just use the right function or prefix. The key is knowing when to use each and being cautious with input formats.
The above is the detailed content of Working with Binary, Octal, and Hexadecimal Number Systems in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

UseIntl.NumberFormatwithuser-specificlocalesforcorrectdigitgroupinganddecimalseparators.2.Formatcurrencyusingstyle:'currency'withISO4217codesandlocale-specificsymbolplacement.3.ApplycompactnotationforlargenumberstoenhancereadabilitywithunitslikeMor??

mt_rand()isnotsecureforcryptographicpurposesbecauseitusestheMersenneTwisteralgorithm,whichproducespredictableoutput,maybepoorlyseeded,andisnotdesignedforsecurity.2.Forsecurerandomnumbergeneration,userandom_int()instead,asitdrawsfromtheoperatingsystem

Using BCMath extension is the key to solving the accuracy of PHP financial calculations, because it performs decimal operations with arbitrary precision through strings, avoiding rounding errors of floating-point numbers; 2. You must always pass in the form of a string and set the scale parameters (such as bcadd('0.1','0.2',2)) to ensure that the result is accurate to the required decimal places; 3. Avoid passing the floating-point numbers directly to the BCMath function, because the accuracy has been lost before passing the parameters; 4. You can set the global decimal places through bccale(2) to ensure that the financial calculation retains two decimals uniformly; 5. BCMath default truncation rather than rounding, and you need to implement the rounding logic yourself (such as through the bcround function); 6. The input value needs to be verified.

When it is necessary to process integers exceeding PHP_INT_MAX (such as 9223372036854775807), 1. Any precision mathematical library such as GMP extension or brick/math should be used; 2. GMP is based on C library, with high performance but requires server support; 3. Brick/math is a pure PHP implementation, which is easy to port but slower; 4. When initializing large numbers, strings must be used to prevent accuracy loss; 5. All operations should avoid floating-point numbers to ensure accuracy. The final choice depends on the degree of environmental control, performance requirements and code style preferences, but large integers need to be safely initialized in strings.

PHP's loose type system is both powerful and dangerous in numeric type conversion. 1. When using loose comparison (==), PHP will convert non-numeric strings to 0, resulting in 'hello'==0 to true, which may cause security vulnerabilities. Strict comparisons (===) should always be used when needed. 2. In arithmetic operation, PHP will silently convert the string, such as '10apples' becomes 10, and 'apples10' becomes 0, which may cause calculation errors. The input should be verified using is_numeric() or filter_var(). 3. In the array key, a numeric string such as '123' will be converted into an integer, causing '007' to become 7, and the format is lost, which can be avoided by adding a prefix. 4. Function parameters

is_numeric()checksifavaluecanbeinterpretedasanumber,acceptingformatslikehex,scientificnotation,andwhitespace,butonlyreturnsabooleanwithouttypecasting.2.filter_var()withFILTER_VALIDATE_INTorFILTER_VALIDATE_FLOATvalidatesandsanitizesbyreturningtheactua

The problem of inaccurate floating point numbers is common in PHP, especially in financial calculations or precise comparisons. The root cause is that decimal decimals cannot be stored accurately in binary floating point representation (IEEE754 standard), resulting in results such as 0.1 0.2≠0.3; 1. When comparing floating point numbers equality, you should use tolerance values (epsilon) instead of directly using ==; 2. Financial calculations should avoid using floating point numbers, and instead use integers (such as in units of division) or BCMath extension; 3. BCMath performs arbitrary precision calculations through strings, which are suitable for high-precision scenarios, but have low performance; 4. It should be noted that PHP type conversion may implicitly convert strings or integers to floating point numbers to introduce errors; in short, inaccurate floating point numbers is a general calculation problem, but in

intdiv()performstrueintegerdivisionandissaferforwholenumbers,whilecasting(int)afterdivisionrisksfloating-pointprecisionerrors.2.Bothtruncatetowardzero,butcastingcanyieldincorrectresultswithnegativeorimprecisevaluesduetofloatrepresentationissues.3.int
