Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 62 / 68

Converting Number Bases (Binary, Hex)

In this lesson you will learn to convert numbers to binary and hexadecimal in PHP and understand the basic idea of base conversion. This is for anyone searching for "PHP base conversion decbin dechex".

decbin() converts decimal to binary and dechex() to hexadecimal. Going the other way, bindec() turns a binary string back into decimal. Inside the computer, numbers are handled in exactly these bases.

The sample code converts 42 into a binary string with decbin() and into a hexadecimal string with dechex(). Going back, bindec("101010") returns the decimal 42, confirming the round trip.

A common stumbling block for beginners is connecting the function names to what they do. decbin is "decimal to binary" and dechex is "decimal to hexadecimal" - once you see the naming pattern they are easy to remember.

Hexadecimal turns up in colour codes, making this handy background knowledge for web development. For octal there is decoct(), built on exactly the same idea.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)