Binary, Hexadecimal, Octal Functions in PHP
Function Name | Function Description |
---|---|
base_convert() | Convert a number between arbitrary bases |
bindec() | Binary to decimal |
decbin() | Decimal to binary |
dechex() | Decimal to hexadecimal |
decoct() | Decimal to octal |
hexdec() | Hexadecimal to decimal |
octdec() | Octal to decimal |
PHP base_convert()
Function
PHP base_convert()
Usage
The PHP
function will convert a number between arbitrary bases.base_convert()
PHP base_convert()
Syntax
base_convert ( string $number , int $frombase , int $tobase ) : string
PHP base_convert()
Parameters
number
— The number to convert. Any invalid characters in number are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated.frombase
— The base number is intobase
— The base to convert number to
PHP base_convert()
Return Value
The PHP base_convert()
function returns number
converted to base tobase
PHP base_convert()
Working Examples
1. base_convert() example
<?php
$hexadecimal = 'a37334';
echo base_convert($hexadecimal, 16, 2);
?>
Output of the above code:
101000110111001100110100
Changelog for PHP base_convert() Function
7.4.0 — Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
Important Points about PHP base_convert()
Function
base_convert()
may lose precision on large numbers due to properties related to the internal “double” or “float” type used. Please see the Floating point numbers section in the manual for more specific information and limitations.
Additional Tips from Fellow Developers
Contributed By: PHPCoder
Convert an arbitrarily large number from any base to any base.
string convBase(string $numberInput, string $fromBaseInput, string $toBaseInput)
$numberInput number to convert as a string
$fromBaseInput base of the number to convert as a string
$toBaseInput base the number should be converted to as a string
examples for $fromBaseInput and $toBaseInput
'0123456789ABCDEF' for Hexadecimal (Base16)
'0123456789' for Decimal (Base10)
'01234567' for Octal (Base8)
'01' for Binary (Base2)
You can really put in whatever you want and the first character is the 0.
Examples:
<?php
convBase('123', '0123456789', '01234567');
//Convert '123' from decimal (base10) to octal (base8).
//result: 173
convBase('70B1D707EAC2EDF4C6389F440C7294B51FFF57BB', '0123456789ABCDEF', '01');
//Convert '70B1D707EAC2EDF4C6389F440C7294B51FFF57BB' from hexadecimal (base16) to binary (base2).
//result:
//111000010110001110101110000011111101010110000101110
//110111110100110001100011100010011111010001000000110
//001110010100101001011010100011111111111110101011110
//111011
convBase('1324523453243154324542341524315432113200203012', '012345', '0123456789ABCDEF');
//Convert '1324523453243154324542341524315432113200203012' from senary (base6) to hexadecimal (base16).
//result: 1F9881BAD10454A8C23A838EF00F50
convBase('355927353784509896715106760','0123456789','Christopher');
//Convert '355927353784509896715106760' from decimal (base10) to undecimal (base11) using "Christopher" as the numbers.
//result: iihtspiphoeCrCeshhorsrrtrh
convBase('1C238Ab97132aAC84B72','0123456789aAbBcCdD', '~!@#$%^&*()');
//Convert'1C238Ab97132aAC84B72' from octodecimal (base18) using '0123456789aAbBcCdD' as the numbers to undecimal (base11) using '~!@#$%^&*()' as the numbers.
//result: !%~!!*&!~^!!&(&!~^@#@@@&
function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
if ($fromBaseInput==$toBaseInput) return $numberInput;
$fromBase = str_split($fromBaseInput,1);
$toBase = str_split($toBaseInput,1);
$number = str_split($numberInput,1);
$fromLen=strlen($fromBaseInput);
$toLen=strlen($toBaseInput);
$numberLen=strlen($numberInput);
$retval='';
if ($toBaseInput == '0123456789')
{
$retval=0;
for ($i = 1;$i <= $numberLen; $i++)
$retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
return $retval;
}
if ($fromBaseInput != '0123456789')
$base10=convBase($numberInput, $fromBaseInput, '0123456789');
else
$base10 = $numberInput;
if ($base10<strlen($toBaseInput))
return $toBase[$base10];
while($base10 != '0')
{
$retval = $toBase[bcmod($base10,$toLen)].$retval;
$base10 = bcdiv($base10,$toLen,0);
}
return $retval;
}
?>
Contributed By: JR
Short arabic2roman conveter:
<?php
function rome($N){
$c='IVXLCDM';
for($a=5,$b=$s='';$N;$b++,$a^=7)
for($o=$N%$a,$N=$N/$a^0;$o--;$s=$c[$o>2?$b+$N-($N&=-2)+$o=1:$b].$s);
return $s;
}
?>
And it works :)
Contributed By: Clifford dot ct
If you use base_convert to convert a large (eg. 80-bit) hexadecimal to base-36, you might observe:
ABCDEF00001234567890 (hexadecimal) => 3O47RE02JZSW0KS8 (base-36) => ABCDEF00001240000000 (hexadecimal)
This is normal and is due to the loss of precision on large numbers.
I have written a string-based function using the built-in BC Math Extension which will overcome this and similar problems.
<?php
function str_baseconvert($str, $frombase=10, $tobase=36) {
$str = trim($str);
if (intval($frombase) != 10) {
$len = strlen($str);
$q = 0;
for ($i=0; $i<$len; $i++) {
$r = base_convert($str[$i], $frombase, 10);
$q = bcadd(bcmul($q, $frombase), $r);
}
}
else $q = $str;
if (intval($tobase) != 10) {
$s = '';
while (bccomp($q, '0', 0) > 0) {
$r = intval(bcmod($q, $tobase));
$s = base_convert($r, 10, $tobase) . $s;
$q = bcdiv($q, $tobase, 0);
}
}
else $s = $q;
return $s;
}
?>
Typical use-cases:
1. Convert a large arbitrary precision number to base-36.
2. Convert a 32-char hexadecimal UUID (128-bit) to a 25-char base-36 unique key, and vice versa.
Examples:
<?php
$b16 = 'ABCDEF00001234567890';
$b36 = str_baseconvert($b16, 16, 36);
echo ("$b16 (hexadecimal) = $b36 (base-36) \\n");
$uuid = 'ABCDEF01234567890123456789ABCDEF';
$ukey = str_baseconvert($uuid, 16, 36);
echo ("$uuid (hexadecimal) = $ukey (base-36) \\n");
?>
ABCDEF00001234567890 (hexadecimal) = 3o47re02jzqisvio (base-36)
ABCDEF01234567890123456789ABCDEF (hexadecimal) = a65xa07491kf5zyfpvbo76g33 (base-36)
PHP bindec()
Function
PHP bindec()
Usage
The PHP
function will give you the decimal equivalent of the binary number represented by the bindec()
binary_string
argument.
PHP bindec()
Syntax
bindec ( string $binary_string ) : number
PHP bindec()
Parameters
binary_string
— The binary string to convert. Any invalid characters in binary_string are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated.
PHP bindec()
Return Value
The PHP bindec()
function returns the decimal value of binary_string
PHP bindec()
Working Examples
1. bindec() example
<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";
echo bindec('111');
?>
Output of the above code:
51
51
7
2. bindec() interprets input as unsigned integers
<?php
/*
* The lesson from this example is in the output
* rather than the PHP code itself.
*/
$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'See the rollover? Watch it next time around...');
p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpreted to be one more than PHP_INT_MAX');
if (PHP_INT_SIZE == 4) {
$note = 'interpreted to be the largest unsigned integer';
} else {
$note = 'interpreted to be the largest unsigned integer
(18446744073709551615) but skewed by float precision';
}
p(-1, $note);
function p($input, $note = '') {
echo "input: $input\n";
$format = '%0' . (PHP_INT_SIZE * 8) . 'b';
$bin = sprintf($format, $input);
echo "binary: $bin\n";
ini_set('precision', 20); // For readability on 64 bit boxes.
$dec = bindec($bin);
echo 'bindec(): ' . $dec . "\n";
if ($note) {
echo "NOTE: $note\n";
}
echo "\n";
}
?>
Output of the above code:
input: 1073741823
binary: 00111111111111111111111111111111
bindec(): 1073741823
input: 1073741824
binary: 01000000000000000000000000000000
bindec(): 1073741824
NOTE: See the rollover? Watch it next time around...
input: 2147483647
binary: 01111111111111111111111111111111
bindec(): 2147483647
NOTE: PHP_INT_MAX
input: -2147483648
binary: 10000000000000000000000000000000
bindec(): 2147483648
NOTE: interpreted to be one more than PHP_INT_MAX
input: -1
binary: 11111111111111111111111111111111
bindec(): 4294967295
NOTE: interpreted to be the largest unsigned integer
Changelog for PHP bindec() Function
7.4.0 — Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
Important Points about PHP bindec()
Function
The parameter must be a string. Using other data types will produce unexpected results.
The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.
PHP decbin()
Function
PHP decbin()
Usage
The PHP
function will give you a string containing a binary representation of the given decbin()
number
argument.
PHP decbin()
Syntax
decbin ( int $number ) : string
PHP decbin()
Parameters
number
— Decimal value to convert
PHP decbin()
Return Value
The PHP decbin()
function returns binary string representation of number
PHP decbin()
Working Examples
1. decbin() example
<?php
echo decbin(12) . "\n";
echo decbin(26);
?>
Output of the above code:
1100
11010
Additional Tips from Fellow Developers
Contributed By: MarcelG
To add leading zeros I prefer the following:
<?php
// Add leading zeros
$bin = sprintf( "%08d", decbin( 26 )); // "00011010"
?>
PHP dechex()
Function
PHP dechex()
Usage
The PHP
function will give you a string containing a hexadecimal representation of the given unsigned dechex()
number
argument.
PHP dechex()
Syntax
dechex ( int $number ) : string
PHP dechex()
Parameters
number
— The decimal value to convert.
PHP dechex()
Return Value
The PHP dechex()
function returns hexadecimal string representation of number
.
PHP dechex()
Working Examples
1. dechex() example
<?php
echo dechex(10) . "\n";
echo dechex(47);
?>
Output of the above code:
a
2f
2. dechex() example with large integers
<?php
// The output below assumes a 32-bit platform.
// Note that the output is the same for all values.
echo dechex(-1)."\n";
echo dechex(PHP_INT_MAX * 2 + 1)."\n";
echo dechex(pow(2, 32) - 1)."\n";
?>
Output of the above code:
ffffffff
ffffffff
ffffffff
Additional Tips from Fellow Developers
Contributed By: brent
Be very careful calling dechex on a number if it's stored in a string.
For instance:
The max number it can handle is 4294967295 which in hex is FFFFFFFF, as it says in the documentation.
dechex(4294967295) => FFFFFFFF //CORRECT
BUT, if you call it on a string of a number, it casts to int, and automatically gives you the largest int it can handle.
dechex('4294967295') => 7FFFFFFF //WRONG!
so you'll need to cast to a float:
dechex((float) '4294967295') => FFFFFFFF //CORRECT
This took me FOREVER to figure out, so hopefully I just saved someone some time.
Contributed By: joost
Here are two functions that will convert large dec numbers to hex and vice versa. And I really mean LARGE, much larger than any function posted earlier.
<pre>
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
$hexvalues = array('0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F');
$hexval = '';
while($number != '0')
{
$hexval = $hexvalues[bcmod($number,'16')].$hexval;
$number = bcdiv($number,'16',0);
}
return $hexval;
}
// Input: A hexadecimal number as a String.
// Output: The equivalent decimal number as a String.
function hex2dec($number)
{
$decvalues = array('0' => '0', '1' => '1', '2' => '2',
'3' => '3', '4' => '4', '5' => '5',
'6' => '6', '7' => '7', '8' => '8',
'9' => '9', 'A' => '10', 'B' => '11',
'C' => '12', 'D' => '13', 'E' => '14',
'F' => '15');
$decval = '0';
$number = strrev($number);
for($i = 0; $i < strlen($number); $i++)
{
$decval = bcadd(bcmul(bcpow('16',$i,0),$decvalues[$number{$i}]), $decval);
}
return $decval;
}
</pre>
PHP decoct()
Function
PHP decoct()
Usage
The PHP
function will give you a string containing an octal representation of the given decoct()
number
argument. The largest number that can be converted depends on the platform in use. For 32-bit platforms this is usually 4294967295 in decimal resulting in 37777777777. For 64-bit platforms this is usually 9223372036854775807 in decimal resulting in 777777777777777777777.
PHP decoct()
Syntax
decoct ( int $number ) : string
PHP decoct()
Parameters
number
— Decimal value to convert
PHP decoct()
Return Value
The PHP decoct()
function returns octal string representation of number
PHP decoct()
Working Examples
1. decoct() example
<?php
echo decoct(15) . "\n";
echo decoct(264);
?>
Output of the above code:
17
410
PHP hexdec()
Function
PHP hexdec()
Usage
The PHP
function will give you the decimal equivalent of the hexadecimal number represented by the hexdec()
hex_string
argument. hexdec()
converts a hexadecimal string to a decimal number.
PHP hexdec()
Syntax
hexdec ( string $hex_string ) : number
PHP hexdec()
Parameters
hex_string
— The hexadecimal string to convert
PHP hexdec()
Return Value
The PHP hexdec()
function returns the decimal representation of hex_string
PHP hexdec()
Working Examples
1. hexdec() example
<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"
var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>
Changelog for PHP hexdec() Function
7.4.0 — Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
Important Points about PHP hexdec()
Function
The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.
Additional Tips from Fellow Developers
Contributed By: hafees
Use this function to convert a hexa decimal color code to its RGB equivalent. Unlike many other functions provided here, it will work correctly with hex color short hand notation.
Also, if a proper hexa decimal color value is given (6 digits), it uses bit wise operations for faster results.
For eg: #FFF and #FFFFFF will produce the same result
<?php
/**
* Convert a hexa decimal color code to its RGB equivalent
*
* @param string $hexStr (hexadecimal color value)
* @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
* @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
* @return array or string (depending on second parameter. Returns False if invalid hex color value)
*/
function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
$hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
$rgbArray = array();
if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
$colorVal = hexdec($hexStr);
$rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
$rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
$rgbArray['blue'] = 0xFF & $colorVal;
} elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
$rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
$rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
$rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
} else {
return false; //Invalid hex color code
}
return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
} ?>
OUTPUT:
hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> Same as above
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0
PHP octdec()
Function
PHP octdec()
Usage
The PHP
function will give you the decimal equivalent of the octal number represented by the octdec()
octal_string
argument.
PHP octdec()
Syntax
octdec ( string $octal_string ) : number
PHP octdec()
Parameters
octal_string
— The octal string to convert. Any invalid characters in octal_string are silently ignored. As of PHP 7.4.0 supplying any invalid characters is deprecated.
PHP octdec()
Return Value
The PHP octdec()
function returns the decimal representation of octal_string
PHP octdec()
Working Examples
1. octdec() example
<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>
Output of the above code:
63
45
Changelog for PHP octdec() Function
7.4.0 — Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.
Important Points about PHP octdec()
Function
The function can convert numbers that are too large to fit into the platforms integer type, larger values are returned as float in that case.
Rate this post —
thank you for sharing