Converting decimal to other number systems with PHP

Josh Sherman
1 min read
Software Development PHP

It felt a bit like cheating to split this post up so I figured I would just cover all of the decimal to… functions in one post. Decimal, also known as base ten, is the numerical base we are most accustomed to. From time to time we need to convert a decimal number to another number system like binary or hex. PHP comes with 3 functions for that very purpose as well as a fourth that can be used to convert between arbitrary bases:

$decimal = 100;

echo 'Binary:      ' . decbin($decimal) . "\n";
echo 'Hexadecimal: ' . dechex($decimal) . "\n";
echo 'Octal:       ' . decoct($decimal) . "\n";

Those are the shorthand functions, which also have related functions to allow you to go in the other direction as well: bindec(), hexdec() and octdec().

To do base conversions outside of these common number systems, you can use base_convert() which takes 3 arguments. First, the number you want to convert, followed by the base you’re starting with and the base you want to convert to:

$decimal = 12345;
echo 'Base 24: ' . base_convert($decimal, 10, 24);

Fun tip, URL shorteners tend to use base conversion to take integer IDs stored in a database and convert them to a shorter alphanumeric string!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles