dechex

(PHP 4, PHP 5, PHP 7, PHP 8)

dechex β€” ΠŸΠ΅Ρ€Π΅Π²ΠΎΠ΄ΠΈΡ‚ число ΠΈΠ· дСсятичной систСмы счислСния Π² ΡˆΠ΅ΡΡ‚Π½Π°Π΄Ρ†Π°Ρ‚Π΅Ρ€ΠΈΡ‡Π½ΡƒΡŽ

ОписаниС

function dechex(int $num): string

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ строку, ΡΠΎΠ΄Π΅Ρ€ΠΆΠ°Ρ‰ΡƒΡŽ ΡˆΠ΅ΡΡ‚Π½Π°Π΄Ρ†Π°Ρ‚Π΅Ρ€ΠΈΡ‡Π½ΠΎΠ΅ прСдставлСниС Π·Π°Π΄Π°Π½Π½ΠΎΠ³ΠΎ Π±Π΅Π·Π·Π½Π°ΠΊΠΎΠ²ΠΎΠ³ΠΎ Π°Ρ€Π³ΡƒΠΌΠ΅Π½Ρ‚Π° num.

НаибольшСС число, ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ΅ функция ΠΏΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΡƒΠ΅Ρ‚, β€” PHP_INT_MAX * 2 + 1 (ΠΈΠ»ΠΈ -1): Π½Π° 32-Π±ΠΈΡ‚Π½Ρ‹Ρ… ΠΏΠ»Π°Ρ‚Ρ„ΠΎΡ€ΠΌΠ°Ρ… это число 4 294 967 295 Π² дСсятСричной систСмС, для ΠΊΠΎΡ‚ΠΎΡ€ΠΎΠ³ΠΎ функция dechex() Π²Π΅Ρ€Π½Ρ‘Ρ‚ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ffffffff.

Бписок ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ΠΎΠ²

num

ДСсятичноС Π·Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ для прСобразования.

ΠŸΠΎΡΠΊΠΎΠ»ΡŒΠΊΡƒ Π² PHP значСния цСлочислСнного Ρ‚ΠΈΠΏΠ° (int) Π·Π½Π°ΠΊΠΎΠ²Ρ‹Π΅, Π° функция dechex() Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚ с Π±Π΅Π·Π·Π½Π°ΠΊΠΎΠ²Ρ‹ΠΌΠΈ Ρ†Π΅Π»Ρ‹ΠΌΠΈ числами, Ρ‚ΠΎ ΠΎΡ‚Ρ€ΠΈΡ†Π°Ρ‚Π΅Π»ΡŒΠ½Ρ‹Π΅ Ρ†Π΅Π»Ρ‹Π΅ числа Π±ΡƒΠ΄ΡƒΡ‚ ΠΎΠ±Ρ€Π°Π±Π°Ρ‚Ρ‹Π²Π°Ρ‚ΡŒΡΡ ΠΊΠ°ΠΊ Π±Π΅Π·Π·Π½Π°ΠΊΠΎΠ²Ρ‹Π΅.

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌΡ‹Π΅ значСния

Π’ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅Ρ‚ ΡˆΠ΅ΡΡ‚Π½Π°Π΄Ρ†Π°Ρ‚Π΅Ρ€ΠΈΡ‡Π½ΠΎΠ΅ строковоС прСдставлСниС числа num.

ΠŸΡ€ΠΈΠΌΠ΅Ρ€Ρ‹

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #1 ΠŸΡ€ΠΈΠΌΠ΅Ρ€ использования Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ dechex()

<?php

echo dechex(10) . "\n";
echo
dechex(47);

?>

Π Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ выполнСния ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°:

a
2f

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #2 ΠŸΡ€ΠΈΠΌΠ΅Ρ€ использования Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ dechex() с большими Ρ†Π΅Π»Ρ‹ΠΌΠΈ числами

<?php
// Π’Ρ‹Π²ΠΎΠ΄ ΠΏΠΎΠ΄Ρ€Π°Π·ΡƒΠΌΠ΅Π²Π°Π΅Ρ‚ 32-Π±ΠΈΡ‚Π½ΡƒΡŽ ΠΏΠ»Π°Ρ‚Ρ„ΠΎΡ€ΠΌΡƒ.
// ΠžΠ±Ρ€Π°Ρ‚ΠΈΡ‚Π΅ Π²Π½ΠΈΠΌΠ°Π½ΠΈΠ΅, Ρ‡Ρ‚ΠΎ Π²Ρ‹Π²ΠΎΠ΄ ΠΎΠ΄ΠΈΠ½Π°ΠΊΠΎΠ² для всСх Π·Π½Π°Ρ‡Π΅Π½ΠΈΠΉ.
echo dechex(-1)."\n";
echo
dechex(PHP_INT_MAX * 2 + 1)."\n";
echo
dechex(pow(2, 32) - 1)."\n";

?>

Π Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ выполнСния ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°:

ffffffff
ffffffff
ffffffff

Π‘ΠΌΠΎΡ‚Ρ€ΠΈΡ‚Π΅ Ρ‚Π°ΠΊΠΆΠ΅

  • hexdec() - ΠŸΠ΅Ρ€Π΅Π²ΠΎΠ΄ΠΈΡ‚ число ΠΈΠ· ΡˆΠ΅ΡΡ‚Π½Π°Π΄Ρ†Π°Ρ‚Π΅Ρ€ΠΈΡ‡Π½ΠΎΠΉ систСмы счислСния Π² Π΄Π΅ΡΡΡ‚ΠΈΡ‡Π½ΡƒΡŽ
  • decbin() - ΠŸΠ΅Ρ€Π΅Π²ΠΎΠ΄ΠΈΡ‚ число ΠΈΠ· дСсятичной систСмы счислСния Π² Π΄Π²ΠΎΠΈΡ‡Π½ΡƒΡŽ
  • decoct() - ΠŸΠ΅Ρ€Π΅Π²ΠΎΠ΄ΠΈΡ‚ число ΠΈΠ· дСсятичной систСмы счислСния Π² Π²ΠΎΡΡŒΠΌΠ΅Ρ€ΠΈΡ‡Π½ΡƒΡŽ
  • base_convert() - ΠŸΡ€Π΅ΠΎΠ±Ρ€Π°Π·ΠΎΠ²Ρ‹Π²Π°Π΅Ρ‚ числа ΠΌΠ΅ΠΆΠ΄Ρƒ ΠΏΡ€ΠΎΠΈΠ·Π²ΠΎΠ»ΡŒΠ½Ρ‹ΠΌΠΈ систСмами счислСния
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 18 notes

up
90
brent ΒΆ
19 years ago
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.
up
2
sneskid at hotmail dot com ΒΆ
14 years ago
If you want to create or parse signed Hex values:

<?php
// $d should be an int
function sdechex($d) { return ($d<0) ? ('-' . dechex(-$d)) : dechex($d); }

// $h should be a string
function shexdec($h) { return ($h[0] === '-') ? -('0x' . substr($h,1) + 0) : ('0x' . $h + 0); }

// test

$v = sdechex(-123); // string(3) "-7b"
$i = shexdec($v);   // int(-123)
var_dump($v, $i);
?>

Also note that ('0x' . $str + 0) is faster than hexdec()
up
5
mina86 at tlen dot pl ΒΆ
22 years ago
Easiest :P way to create random hex color:

<?php
function rand_color() {
    return substr('00000' . dechex(mt_rand(0, 0xffffff)), -6);
}
?>
up
6
Anonymous ΒΆ
21 years ago
If you need to generate random HEX-color, use this:
<?php
function random_hex_color(){
    return sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
}
$hex = random_hex_color(); // 09B826
?>

Enjoy.
up
14
joost at bingopaleis dot com ΒΆ
24 years ago
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>
up
1
mahdiyari ΒΆ
3 years ago
Zero padded hex strings as a pair of 2 (8bit).

<?php 
function dec2hex($int) {
  $hex = dechex($int);
  if (strlen($hex)%2 != 0) {
    $hex = str_pad($hex, strlen($hex) + 1, '0', STR_PAD_LEFT);
  }
  return $hex;
}

dec2hex(2); // 02
dec2hex(10); // 0a
dec2hex(256); // 0100
?>
up
2
delchodimi at gmail dot com ΒΆ
11 years ago
I like the example with the bitwise operations but if the value of color[0] is less than 16 it's not accurate:
example:
color[0]: 0;
color[1]: 0;
color[2]: 255;
 function hexColor($color) {
  return dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
}
It returns "ff", which is not legit RGB color...
so my solution is to combine the function above with: 
function toColor($n)
{
return("#".substr("000000".dechex($n),-6));
}

If you gotta deal with array of rgb values this is my solution:
------------------------------------------------------
function hexColor($color) {
    $rgb = dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
    return("#".substr("000000".$rgb, -6));
}
------------------------------------------------------
up
7
jrisken at mn dot rr dot com ΒΆ
21 years ago
A less elegant but (perhaps) faster way to pad is with substr with a negative length argument. I use it in this tiny function which formats computed rgb color codes for style sheets:
<?
function toColor($n)
{
return("#".substr("000000".dechex($n),-6));
}
?>
up
2
mountarreat at gmail dot com ΒΆ
18 years ago
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex.

In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h.

Of course I don't claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome!

<?php
// Turns numbers into 32-bit hex string; Fills up zeros
function lrgDec2Hex($number)
{
    $i = 0;
    $hex = array();

    while($i < 8) {
        if($number == 0) {
            array_push($hex, '0');
        }
        else {
            array_push($hex, strtoupper(dechex(bcmod($number, '16'))));
            $number = bcdiv($number, '16', 0);
        }
        $i++;
    }
    krsort($hex);
    return implode($hex);
}
?>
up
1
baoquyen804 at gmail dot com ΒΆ
11 years ago
this base function convert string rgb to color
<?php
    function rgb_to_color($rgb, $symbols=' '){
        $color = '';
        $arr = explode($symbols, $rgb);
        $count = count($arr);
        for($i=0; $i<$count; $i++){
            $color .= dechex($arr[$i]);
        }
        return '#'.$color;
    }
       echo rgb_to_color('186 186 18');  // #baba12
    echo rgb_to_color('186-186-18', '-');  // #baba12
?>
up
2
huda m elmatsani <justhuda at netscape dot net> ΒΆ
22 years ago
Create Random Hex Color:

function make_seed() { 
   list($usec, $sec) = explode(' ', microtime()); 
   return (float) $sec + ((double) $usec * 100000); 
} 

function rand_hex() {
   mt_srand(make_seed()); 
   $randval = mt_rand(0,255);
   //convert to hex
   return sprintf("%02X",$randval);
}

function random_color(){
   return "#".rand_hex().rand_hex().rand_hex();
}

hme ;)
up
3
admin AT bobfrank DOT org ΒΆ
21 years ago
Here is a very small zeropadding that you can use for numbers:

function zeropad($num, $lim)
{
   return (strlen($num) >= $lim) ? $num : zeropad("0" . $num);
}

zeropad("234",6);

will produce:
000234

zeropad("234",1);

will produce:
234
up
3
andries at centim dot be ΒΆ
14 years ago
If you need to convert a large number (> PHP_MAX_INT) to a hex value, simply use base_convert. For example:

base_convert('2190964402', 10, 16); // 829776b2
up
2
Anonymous ΒΆ
21 years ago
If you need to convert RGB-color into HEX-color, use this:
<?php
function rgb2hex($rgb){
    return sprintf("%06X", $rgb);
}
$hex = rgb2hex(65280); // 00FF00
?>
up
2
jbleau at gmail dot com ΒΆ
17 years ago
I was confused by dechex's size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs.

<?php
function dec_to_hex($dec)
{
    $sign = ""; // suppress errors
    if( $dec < 0){ $sign = "-"; $dec = abs($dec); }

    $hex = Array( 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
                  6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 'a',
                  11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e',    
                  15 => 'f' );
        
    do
    {
        $h = $hex[($dec%16)] . $h;
        $dec /= 16;
    }
    while( $dec >= 1 );
    
    return $sign . $h;
}
?>
up
1
monkyNOSPAM at phpfi dot org dot invalid ΒΆ
23 years ago
Here's how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by gurke@bigfoot.com above.

function hexColor($color) {
  return dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
}

example:

$col[0] = 25;
$col[1] = 255;
$col[2] = 55;

print hexColor($col);
up
1
mattgrahamatc at gmail dot com ΒΆ
6 months ago
Arguing a float to dechex, as is commonly recommended as a solution to get around this function's limited range, is a fatal error as of php 8.
up
0
Mista-NiceGuy at web dot de ΒΆ
20 years ago
These are functions to convert roman numbers (e.g. MXC) into dec and vice versa.
Note: romdec() does not check whether a string is really roman or not. To force a user-input into a real roman number use decrom(romdec($input)). This will turn XXXX into XL for example.

<?php
    function decrom($dec){
        $digits=array(
            1 => "I",
            4 => "IV",
            5 => "V",
            9 => "IX",
            10 => "X",
            40 => "XL",
            50 => "L",
            90 => "XC",
            100 => "C",
            400 => "CD",
            500 => "D",
            900 => "CM",
            1000 => "M"
        );
        krsort($digits);
        $retval="";
        foreach($digits as $key => $value){
            while($dec>=$key){
                $dec-=$key;
                $retval.=$value;
            }
        }
        return $retval;
    }

    function romdec($rom){
        $digits=array(
            "I" => 1,
            "V" => 5,
            "X" => 10,
            "L" => 50,
            "C" => 100,
            "D" => 500,
            "M" => 1000
        );
        $retval="";
        $chars=array();
        for($i=1;$i<=strlen($rom);$i++){
            $chars[]=substr($rom,$i-1,1);
        }
        $step=1;
        for($i=count($chars)-1;$i>=0;$i--){
            if(!isset($digits[$chars[$i]])){ return "Error!"; }
            if($step<=$digits[$chars[$i]]){
                $step=$digits[$chars[$i]];
                $retval+=$digits[$chars[$i]];
            }
            else{
                $retval-=$digits[$chars[$i]];
            }
        }
        return $retval;
    }

    echo decrom(romdec("XXXX"));
?>