Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert a number to binary or hexadecimal

Short answer

decbin() and dechex() return the number's notation as a string:

<?php
 
echo decbin(10), ' ', dechex(255);

Output:

1010 ff

Back to decimal

bindec() and hexdec() do that:

<?php
 
echo bindec('1010'), ' ', hexdec('ff');

Output:

10 255

Any base

base_convert() converts between bases from 2 to 36:

<?php
 
echo base_convert('255', 10, 2), ' ', base_convert('zz', 36, 10);

Output:

11111111 1295

Numbers in code

In the program itself numbers can be written with the 0b, 0o and 0x prefixes:

<?php
 
echo 0b1010, ' ', 0o17, ' ', 0xff;

Output:

10 15 255

Functions used in this recipe

  • decbin — Converts a number to binary.
  • dechex — Converts a number to hexadecimal.
  • base_convert — Converts a number from one base to another.

Thanks for reading!

Donate to the site — we work hard for you.