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 ffBack to decimal
bindec() and hexdec() do that:
<?php
echo bindec('1010'), ' ', hexdec('ff');Output:
10 255Any base
base_convert() converts between bases from 2 to 36:
<?php
echo base_convert('255', 10, 2), ' ', base_convert('zz', 36, 10);Output:
11111111 1295Numbers 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 255Functions 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.