hexdec

(PHP 4, PHP 5, PHP 7)

hexdec十六进制转换为十进制

说明

number hexdec ( string $hex_string )

返回与 hex_string 参数所表示的十六进制数等值的的十进制数。hexdec() 将一个十六进制字符串转换为十进制数。

hexdec() 会忽略它遇到的任意非十六进制的字符。

参数

hex_string

要转换的十六进制的字符串

返回值

hex_string 十进制的表示

更新日志

版本 说明
4.1.0 PHP 4.1.0 开始,该函数可以处理 integer 大数字,这种情况下,它会返回 float 类型。

范例

Example #1 hexdec() 例子

<?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)"
?>

参见

User Contributed Notes

helpmedalph at gmail dot com 02-May-2016 11:31
function hex2rgb($hex) {
    if ($hex[0]=='#') $hex = substr($hex,1);
    if (strlen($hex)==3){
        $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    }
    $int = hexdec($hex);
    return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
Ulf 20-Aug-2013 07:51
Instead of chuckySTAR's cool bchexdec() function you could also just use
base_convert("fffffffffffffffffffffffffffffffff", 16, 10)
to convert hex values of any size to a decimal string.
holdoffhunger at gmail dot com 26-Jun-2012 03:29
When given large numbers, the hexdec function automatically converts the value to scientific notation.  So, "aa1233123124121241" as a hexadecimal value will be converted to "3.13725790445E+21".  If you're converting a hexadecimal value that represents a hash value (md5 or sha), then you need every single bit of that representation to make it useful.  By using the number_format function, you can do that perfectly.  For example :

<?php

           
// Author: holdoffhunger@gmail.com
   
        // Example Hexadecimal
        // ---------------------------------------------

   
$hexadecimal_string = "1234567890abcdef1234567890abcdef";
   
       
// Converted to Decimal
        // ---------------------------------------------

   
$decimal_result = hexdec($hexadecimal_string);
   
       
// Print Pre-Formatted Results
        // ---------------------------------------------

   
print($decimal_result);

           
// Output Here: "2.41978572002E+37"
            // .....................................
   
        // Format Results to View Whole All Digits in Integer
        // ---------------------------------------------

            // ( Note: All fractional value of the
            //         Hexadecimal variable are ignored
            //         in the conversion. )
                   
   
$current_hashing_algorithm_decimal_result = number_format($decimal_result, 0, '', '');
   
       
// Print Formatted Results
        // ---------------------------------------------

   
print($current_hashing_algorithm_decimal_result);

           
// Output Here: "24197857200151253041252346215207534592"
            // .....................................

?>
sneskid at hotmail dot com 24-Mar-2012 11:50
If you want to create or parse signed Hex strings:

<?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
$h = sdechex(-123); // string(3) "-7b"
$d = shexdec($h);   // int(-123)
var_dump($h, $d);
?>

Also note that ('0x' . $hexstr + 0) is faster than hexdec()
(Tested on PHP v5.2.17)
programacion at mundosica dot com 07-Dec-2011 06:50
Here is other function to transform a MAC Address to decimal:

<?php
function get_mac_decimal($mac) {
   
$clear_mac = preg_replace('/[^0-9A-F]/i','',$mac);
   
$mac_decimal = array();
    for (
$i = 0; $i < strlen($clear_mac); $i += 2 ):
       
$mac_decimal[] = hexdec(substr($clear_mac, $i, 2));
    endfor;
    return
implode('.',$mac_decimal);
}
?>
andy at haveland dot com 25-Oct-2010 07:55
Here's a short example to convert strings between hex and chars:

<?php
print hextostr("616E647940686176656C616E642E636F6D")."\n";

print
strtohex("Knowledge is power")."\n";

function
hextostr($x) {
 
$s='';
  foreach(
explode("\n",trim(chunk_split($x,2))) as $h) $s.=chr(hexdec($h));
  return(
$s);
}

function
strtohex($x) {
 
$s='';
  foreach(
str_split($x) as $c) $s.=sprintf("%02X",ord($c));
  return(
$s);
}
?>
hafees at msn dot com 19-Aug-2010 12:31
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
Rosberg - rosberglinhares at gmail dot com 06-May-2010 05:45
The correct version is:

function bchexdec($hex) {
    static $hexdec = 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
    );

    $dec = 0;

    for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
        $factor = $hexdec[$hex[$i]];
        $dec = bcadd($dec, bcmul($factor, $e));
    }

    return $dec;
}
flurinj at gmx dot net 06-Apr-2010 04:13
Here My version of converting a hex string to a signed decimal value:

<?php

function hexdecs($hex)
{
   
// ignore non hex characters
   
$hex = preg_replace('/[^0-9A-Fa-f]/', '', $hex);
   
   
// converted decimal value:
   
$dec = hexdec($hex);
   
   
// maximum decimal value based on length of hex + 1:
    //   number of bits in hex number is 8 bits for each 2 hex -> max = 2^n
    //   use 'pow(2,n)' since '1 << n' is only for integers and therefore limited to integer size.
   
$max = pow(2, 4 * (strlen($hex) + (strlen($hex) % 2)));
   
   
// complement = maximum - converted hex:
   
$_dec = $max - $dec;
   
   
// if dec value is larger than its complement we have a negative value (first bit is set)
   
return $dec > $_dec ? -$_dec : $dec;
}

?>
Halit YEL - halityesil at globya dot net 02-Oct-2009 10:30
RGB to Hex
Hex to RGB
Function

<?PHP

function rgb2hex2rgb($c){
   if(!
$c) return false;
  
$c = trim($c);
  
$out = false;
  if(
preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){
     
$c = str_replace('#','', $c);
     
$l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false);

      if(
$l){
         unset(
$out);
        
$out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l));
        
$out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l));
        
$out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l));
      }else
$out = false;
             
   }elseif (
preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){
     
$spr = str_replace(array(',',' ','.'), ':', $c);
     
$e = explode(":", $spr);
      if(
count($e) != 3) return false;
        
$out = '#';
         for(
$i = 0; $i<3; $i++)
           
$e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));
             
         for(
$i = 0; $i<3; $i++)
           
$out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];
                 
        
$out = strtoupper($out);
   }else
$out = false;
         
   return
$out;
}

?>

Output

#FFFFFF =>
 Array{
   red=>255,
   green=>255,
   blue=>255,
   r=>255,
   g=>255,
   b=>255,
   0=>255,
   1=>255,
   2=>255
 }
 

#FFCCEE =>
 Array{
   red=>255,
   green=>204,
   blue=>238,
   r=>255,
   g=>204,
   b=>238,
   0=>255,
   1=>204,
   2=>238
 }
CC22FF =>
 Array{
   red=>204,
   green=>34,
   blue=>255,
   r=>204,
   g=>34,
   b=>255,
   0=>204,
   1=>34,
   2=>255
 }

0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA


[EDIT BY danbrown AT php DOT net - Contains multiple bugfixes by (ajim1417 AT gmail DOT com) on 27-JAN-2010: Replaces typo in explode() and updates eregi() calls to preg_match().]
jose dot rob dot jr at gmail dot com 16-Aug-2009 05:13
I made these functions to pack up to 64 ID's into a mysql unsigned bigint.

ID's cannot repeat, must be <= bit's limit and > 0.

The functions uses php 32 bit's int as unsigned because we don't actually read the number, just the bits. Then 0xFFFFFFFF display -1 but the bit's are there (tested with linux 2.6 i686 and x86_64)

---

This is an other way to make hex to bin conversions:

<?php
function hexbin($hex, $padding = false)
{
   
// Validation
   
$hex = preg_replace('/^(0x|X)?/i', '', $hex);
   
$hex = preg_replace('/[[:blank:]]/', '', $hex);
    if(empty(
$hex))
    {
       
$hex = '0';
    }
    if(!
preg_match('/^[0-9A-F]*$/i', $hex))
    {
       
trigger_error('Argument is not a hex', E_USER_WARNING);
        return
false;
    }
   
   
// Conversion
   
$bin = '';
   
$hex = array_reverse(str_split($hex));
    foreach(
$hex as $n)
    {
       
$n = hexdec($n);
        for(
$i = 1; $i <= 8; $i <<= 1)
        {
           
$bin .= ($i & $n)? '1' : '0';
        }
        if(
$padding)
        {
           
$bin .= ' ';
        }
    }
    return
ltrim(strrev($bin));
}

// Tests
echo "<b>Debug:</b> <pre>";

// Randomly choosed padded number
var_dump(hexbin('00FF FF8F 7F3F FF1F', true));
// string(79) "0000 0000 1111 1111 1111 1111 1000 1111 0111 1111 0011 1111 1111 1111 0001 1111"

// Yellow RGB
var_dump(hexbin('0xF8F800'));
// string(24) "111110001111100000000000"

// Green RGB (padded)
var_dump(hexbin('0x008800', true));
//string(29) "0000 0000 1000 1000 0000 0000"

die("\n<br>debug");

?>

Have fun ;D
Ultimater at gmail dot com 19-Apr-2009 10:54
hexdec doesn't accept numbers following the period.
What if you have a number like c20.db18?
<?php
function floatinghexdec($str)
{
    list(
$intgr,$hex)=explode('.',$str,2);
   
$intgr=ereg_replace("[^A-Fa-f0-9]", "", $intgr);
   
$hex=ereg_replace("[^A-Fa-f0-9]", "", $hex);
   
$answer=0;
    for(
$i=0;$i < strlen($hex); $i++)
    {
       
$digit=hexdec(substr($hex,$i,1))/16;   // .f is 15/16 because in decimal .9 is 9/10
       
$answer += $digit/pow(16,$i);
    }
return
hexdec($intgr)+$answer;
}

echo
floatinghexdec("ff.ff");//255.99609375
?>
chuckySTAR 15-Apr-2009 10:55
Here's my hexdec function for greater numbers using BC Math

<?php
function bchexdec($hex)
{
   
$len = strlen($hex);
    for (
$i = 1; $i <= $len; $i++)
       
$dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
   
    return
$dec;
}

echo
bchexdec('ffffffffffffffffffffffffffffffff') . "\n" . (pow(2, 128));
?>
joquius at kakugo dot com 24-Sep-2008 03:12
Help a hex-stricken string get back to normal:

<?php
$str
= preg_replace_callback ("/%([a-zA-Z0-9]{2})/", create_function ('$matches', 'return chr (hexdec ($matches[1]));'), $str);
?>
this1is4me at hotmail dot com 27-May-2008 11:46
In reply to Amit Yadav's post (hex to binary conversion):

function binfromdec($num)
{
  $primary = "bit";
  for ($i=1; $i<=16; $i++)
    ${$primary.$i} = 0;
 
  if ($num & 32768)   $bit16  = 1;
  if ($num & 16384)   $bit15  = 1;
  if ($num & 8192)    $bit14  = 1;
  if ($num & 4096)    $bit13  = 1;
  if ($num & 2048)    $bit12  = 1;
  if ($num & 1024)    $bit11  = 1;
  if ($num & 512)     $bit10  = 1;
  if ($num & 256)     $bit9   = 1;
  if ($num & 128)     $bit8   = 1;
  if ($num & 64)      $bit7   = 1;
  if ($num & 32)      $bit6   = 1;
  if ($num & 16)      $bit5   = 1;
  if ($num & 8)       $bit4   = 1;
  if ($num & 4)       $bit3   = 1;
  if ($num & 2)       $bit2   = 1;
  if ($num & 1)       $bit1   = 1;
 
  return ($bit16. $bit15. $bit14. $bit13. $bit12. $bit11. $bit10. $bit9. $bit8. $bit7. $bit6. $bit5. $bit4. $bit3. $bit2. $bit1);
}
Walter Wlodarski 31-Jan-2008 10:33
One of my favourite, multi-purpose, bidirectional solution I wrote many years ago:

function bgr2rgb($cr) {  // bidirectional
    return (($cr & 0x0000FF) << 16 | ($cr & 0x00FF00) | ($cr & 0xFF0000) >> 16);
}

Which you might want to use as :

function hex2cr($hex) {  // strips any leading characters, like #
    return bgr2rgb(hexdec($hex));
}

function cr2hex($cr) { // the usual HTML format, #rrggbb
    return '#'.str_pad(strtoupper(dechex(bgr2rgb($cr))), 6, '0', STR_PAD_LEFT);
}

And, if like me you tend to mistype function names, the synonym :

function rgb2bgr($val) { return bgr2rgb($val); }
maddddidley at yahoo dot com 27-Jan-2008 09:17
Function that combines two rgb colors.

function combineColors($color1, $color2) {
       
        $color1 = str_replace("#", '', $color1);
        $color2 = str_replace("#", '', $color2);
       
        $r1 = hexdec(substr($color1, 0, 2));
        $g1 = hexdec(substr($color1, 2, 2));
        $b1 = hexdec(substr($color1, 4, 2));
       
        $r2 = hexdec(substr($color2, 0, 2));
        $g2 = hexdec(substr($color2, 2, 2));
        $b2 = hexdec(substr($color2, 4, 2));
       
        $r3 = ceil(($r1 + $r2) / 2);
        $g3 = ceil(($g1 + $g2) / 2);
        $b3 = ceil(($b1 + $b2) / 2);
       
       
        $color = rgbhex($r3, $g3, $b3);
        return $color = str_replace("#", '', $color);
       
    }
Anonymous 14-Nov-2007 05:34
// Fun??o GET Cor Hexadecima e Retorna em RGB
function hexrgb($hexstr, $rgb) {
 $int = hexdec($hexstr);
 switch($rgb) {
        case "r":
        return 0xFF & $int >> 0x10;
            break;
        case "g":
        return 0xFF & ($int >> 0x8);
            break;
        case "b":
        return 0xFF & $int;
            break;
        default:
        return array(
            "r" => 0xFF & $int >> 0x10,
            "g" => 0xFF & ($int >> 0x8),
            "b" => 0xFF & $int
            );
            break;
    }   
}// END GET Cor Hex => RGB

//Uso
 echo hexrgb("1a2b3c", r); // 26
 echo hexrgb("1a2b3c", g); // 43
 echo hexrgb("1a2b3c", b); // 60
//ou

var_dump(hexrgb("1a2b3c", rgb)); //array(3) { ["r"]=>  int(26) ["g"]=>  int(43) ["b"]=>  int(60) }
k10206 at naver dot com 27-Oct-2007 06:42
<?
function hexrgb($hexstr) {
    $int = hexdec($hexstr);

    return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
?>
Manithu 24-Mar-2007 01:23
This tiny function will return foreground colors (either black or white) in contrast to the color you provide:

<?php

function getContrastColor($color)
{
    return (
hexdec($color) > 0xffffff/2) ? '000000' : 'ffffff';
}

?>

This function will return the opposite (negative):

<?php

function negativeColor($color)
{
   
//get red, green and blue
   
$r = substr($color, 0, 2);
   
$g = substr($color, 2, 2);
   
$b = substr($color, 4, 2);
   
   
//revert them, they are decimal now
   
$r = 0xff-hexdec($r);
   
$g = 0xff-hexdec($g);
   
$b = 0xff-hexdec($b);
   
   
//now convert them to hex and return.
   
return dechex($r).dechex($g).dechex($b);
}

?>
cgarvis at gmail dot com 09-Oct-2006 07:39
Here is my version of hex2rgb for web colors to 24bit colors.

<?php
function hex2rgb_webcolors($hex) {
   
$hex = eregi_replace("[^a-fA-F0-9]", "", $hex);
    switch(
strlen($hex) ) {
        case
2:
           
$hex = substr($hex,0,2)."0000";
            break;
        case
3:
           
$hex = substr($hex,0,1).substr($hex,0,1)
            .
substr($hex,1,1).substr($hex,1,1)
            .
substr($hex,2,1).substr($hex,2,1);
            break;
        case
4:
           
$hex = substr($hex,0,4)."00";
            break;
        case
6:
            break;
        default:
           
$hex = 0;
            break;
    }
    return
hexdec($hex);
}
?>
repley at freemail dot it 29-May-2006 03:55
From color to color to ...... to color with fade effect. Good for dynamic bar chart.

<?php
//MultiColorFade(array hex-colors, int steps)
function MultiColorFade($hex_array, $steps) {

$tot = count($hex_array);
$gradient = array();
$fixend = 2;
$passages = $tot-1;
$stepsforpassage = floor($steps/$passages);
$stepsremain = $steps - ($stepsforpassage*$passages);

   for(
$pointer = 0; $pointer < $tot-1 ; $pointer++) {
 
      
$hexstart = $hex_array[$pointer];
      
$hexend = $hex_array[$pointer + 1];

       if(
$stepsremain > 0){
           if(
$stepsremain--){
              
$stepsforthis = $stepsforpassage + 1;
           }
       }else{
          
$stepsforthis = $stepsforpassage;
       }
   
       if(
$pointer > 0){
          
$fixend = 1;        
       }
   
      
$start['r'] = hexdec(substr($hexstart, 0, 2));
      
$start['g'] = hexdec(substr($hexstart, 2, 2));
      
$start['b'] = hexdec(substr($hexstart, 4, 2));

      
$end['r'] = hexdec(substr($hexend, 0, 2));
      
$end['g'] = hexdec(substr($hexend, 2, 2));
      
$end['b'] = hexdec(substr($hexend, 4, 2));
 
      
$step['r'] = ($start['r'] - $end['r']) / ($stepsforthis);
      
$step['g'] = ($start['g'] - $end['g']) / ($stepsforthis);
      
$step['b'] = ($start['b'] - $end['b']) / ($stepsforthis);
   
       for(
$i = 0; $i <= $stepsforthis-$fixend; $i++) {
 
          
$rgb['r'] = floor($start['r'] - ($step['r'] * $i));
          
$rgb['g'] = floor($start['g'] - ($step['g'] * $i));
          
$rgb['b'] = floor($start['b'] - ($step['b'] * $i));
 
          
$hex['r'] = sprintf('%02x', ($rgb['r']));
          
$hex['g'] = sprintf('%02x', ($rgb['g']));
          
$hex['b'] = sprintf('%02x', ($rgb['b']));
 
          
$gradient[] = strtoupper(implode(NULL, $hex));
       }
   }
 
  
$gradient[] = $hex_array[$tot-1];
 
return
$gradient;
}
//end MultiColorFade()

//start test
$multi_hex_array = array();
$multi_hex_array[] = array('FF0000','FFFF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000','FFFFFF');

foreach(
$multi_hex_array as $hex_array){

  
$totcolors = count($hex_array);
  
$steps = 44;

  
$a = MultiColorFade($hex_array, $steps);
  
$tot = count($a);

  
$table = '<table border=1 width="300">' . "\n";

   for (
$i = 0; $i < $tot; $i++){
      
$table .= ' <tr><td bgcolor="' . $a[$i] . '">' . ($i+1) .'</td><td><pre>' . $a[$i] . '</pre></td></tr>' . "\n";
   }
 
  
$table .= '</table><br /><br />';
 
   echo
'<br />Demanded steps = ' . $steps . '<br />';
   echo
'Returned steps = ' . $tot;
 
   if(
$steps == $tot){
       echo
'<br />OK.' . $steps . ' = ' . $tot . '<br />';
   }else{
       echo
'<br /><span style="color:#FF0000">FAILED! Demanded steps and returned steps are NOT equal!: ' . $steps . ' != ' . $tot . '</span><br />';
   }

   echo
$table;
 
}
//end test
?>

Repley.
ayadav at infoprocorp dot com 28-Dec-2005 09:03
From Amit Yadav

Hex to binary conversion

$num = hexdec("20DF");
echo binfromdec($num);

function binfromdec($num)
{
    if ($num > 32766)    return ("Too Large!");
    if ($num & 16384)    $bit15 = 1;
    if ($num & 8192)    $bit14 = 1;
    if ($num & 4096)    $bit13 = 1;
    if ($num & 2048)    $bit12 = 1;
    if ($num & 1024)    $bit11 = 1;
    if ($num & 512)        $bit10 = 1;
    if ($num & 256)        $bit9 = 1;
    if ($num & 128)        $bit8 = 1;
    if ($num & 64)        $bit7 = 1;
    if ($num & 32)        $bit6 = 1;
    if ($num & 16)        $bit5 = 1;
    if ($num & 8)        $bit4 = 1;
    if ($num & 4)        $bit3 = 1;
    if ($num & 2)        $bit2 = 1;
    if ($num & 1)        $bit1 = 1;

    return ("" . $bit15 . $bit14 . $bit13 . $bit12 . $bit11 . $bit10 . $bit9 . $bit8 . $bit7 . $bit6 . $bit5 . $bit4 . $bit3 . $bit2 . $bit1);

}
cory at lavacube dot com 28-Oct-2005 10:59
A handy little function to convert HEX colour codes to "web safe" colours...

<?php

function color_mkwebsafe ( $in )
{
  
// put values into an easy-to-use array
  
$vals['r'] = hexdec( substr($in, 0, 2) );
  
$vals['g'] = hexdec( substr($in, 2, 2) );
  
$vals['b'] = hexdec( substr($in, 4, 2) );

  
// loop through
  
foreach( $vals as $val )
   {
      
// convert value
      
$val = ( round($val/51) * 51 );
      
// convert to HEX
      
$out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
   }

   return
$out;
}

?>

Example: color_mkwebsafe('0e5c94');
Produces: 006699

Hope this helps someone out... Happy coding. :-)
detrate at hotmail dot com 30-Sep-2005 03:38
I made this for a little phpbb mod.  It was used to take the hex value from the database and make a color 20 (in decimal) less, resulting a darker color.

EXAMPLE: #336699 to #1f5285

<?php

$row1
= "336699"; // color
$c = 20;          // difference value

$rgb = array(substr($row1,0,2), substr($row1,2,2), substr($row1,4,2));

for(
$i=0; $i < 3; $i++)
{
  if((
hexdec($rgb[$i])-$c) >= 0)
  {
  
$rgb[$i] = hexdec($rgb[$i])-$c;

  
$rgb[$i] = dechex($rgb[$i]);
    if(
hexdec($rgb[0]) <= 9)
    
$rgb[$i] = "0".$rgb[$i];
  } else {
   
$rgb[$i] = "00";
  }
}

$row2 = $rgb[0].$rgb[1].$rgb[2];

?>
Gabriel Reguly 16-Aug-2005 08:24
After esnhexdec from "rledger at gmail dot com",  the esndechex:

<?php
   
function esndechex($dec){
        
$a = strtoupper(dechex(substr($dec, 12)));
        
$b = strtoupper(dechex(substr($dec, 3, 10)));
         return
$a . $b;
    }
?>
bishop 05-Jun-2005 04:51
Bullet-proof hex-to-rgb colour converter like brian at sagesport dot com wanted, just far fewer code lines. As a bonus, gives you the ability to return as string or array:

<?php
   
function &hex2rgb($hex, $asString = true)
    {
       
// strip off any leading #
       
if (0 === strpos($hex, '#')) {
           
$hex = substr($hex, 1);
        } else if (
0 === strpos($hex, '&H')) {
           
$hex = substr($hex, 2);
        }      

       
// break into hex 3-tuple
       
$cutpoint = ceil(strlen($hex) / 2)-1;
       
$rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

       
// convert each tuple to decimal
       
$rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
       
$rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
       
$rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

        return (
$asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
    }
?>

Handles 2, 3, and 6 character colour codes with leading # or &H.
zubfatal, root at it dot dk 25-Mar-2005 11:36
This replaces my previous class.
I've added a few more input checks in the rgb2hex function.
Also it returned incorrect hex values for 1-digit values.

color::rgb2hex(array(0,0,0)) would output 000 not 00000.

<?php

/**
* Convert colors
*
* Usage:
*  color::hex2rgb("FFFFFF")
*  color::rgb2hex(array(171,37,37))
*
* @author      Tim Johannessen <root@it.dk>
* @version     1.0.1
*/

class color {

   
/**
     * Convert HEX colorcode to an array of colors.
     * @return      array        Returns the array of colors as array(red,green,blue)
     */
    
   
function hex2rgb($hexVal = "") {
       
$hexVal = eregi_replace("[^a-fA-F0-9]", "", $hexVal);
        if (
strlen($hexVal) != 6) { return "ERR: Incorrect colorcode, expecting 6 chars (a-f, 0-9)"; }
       
$arrTmp = explode(" ", chunk_split($hexVal, 2, " "));
       
$arrTmp = array_map("hexdec", $arrTmp);
        return array(
"red" => $arrTmp[0], "green" => $arrTmp[1], "blue" => $arrTmp[2]);
    }
    
   
/**
     * Convert RGB colors to HEX colorcode
     * @return      string        Returns the converted colors as a 6 digit colorcode
     */
   
function rgb2hex($arrColors = null) {
        if (!
is_array($arrColors)) { return "ERR: Invalid input, expecting an array of colors"; }
        if (
count($arrColors) < 3) { return "ERR: Invalid input, array too small (3)"; }
        
       
array_splice($arrColors, 3);
        
        for (
$x = 0; $x < count($arrColors); $x++) {
            if (
strlen($arrColors[$x]) < 1) {
                return
"ERR: One or more empty values found, expecting array with 3 values";
            }
            
            elseif (
eregi("[^0-9]", $arrColors[$x])) {
                return
"ERR: One or more non-numeric values found.";
            }
            
            else {
                if ((
intval($arrColors[$x]) < 0) || (intval($arrColors[$x]) > 255)) {
                    return
"ERR: Range mismatch in one or more values (0-255)";
                }
                
                else {
                   
$arrColors[$x] = strtoupper(str_pad(dechex($arrColors[$x]), 2, 0, STR_PAD_LEFT));
                }
            }
        }
        
        return
implode("", $arrColors);
    }

}

?>
brian at sagesport dot com 22-Mar-2005 06:08
The issue I've seen with the existing hex to dec conversion routines is the lack of error-trapping.  I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one.  I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps.  As such I've seen multiple formats for writing hex colors.

For example, the color red COULD be written as follows:
#ff0000
&Hff0000
#ff
&Hff

Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.

<?php
 
function convert_color($hex){
   
$len = strlen($hex);
   
$chars = array("#","&","H","h");
   
$hex = strip_chars($hex, $chars);
   
preg_match("/([0-9]|[A-F]|[a-f]){".$len."}/i",$hex,$arr);
   
$hex = $arr[0];
    if (
$hex) {
      switch(
$len) {
        case
2:
         
$red = hexdec($hex);
         
$green = 0;
         
$blue = 0;
          break;
        case
4:
         
$red = hexdec(substr($hex,0,2));
         
$green=hexdec(substr($hex,2,2));
         
$blue = 0;
          break;
        case
6:
         
$red = hexdec(substr($hex,0,2));
         
$green=hexdec(substr($hex,2,2));
         
$blue = hexdec(substr($hex,4,2));
          break;      
      };
     
$color[success] = true;
     
$color[r] = $red;
     
$color[g] = $green;
     
$color[b] = $blue;
      return
$color;
    } else {
     
$color[success] = false;
     
$color[error] = "unable to convert hex to dec";
    };
  }

  function
strip_chars($string, $char){
   
$len = strlen($string);
   
$count = count($char);
    if (
$count >= 2) {
      for (
$i=0;$i<=$count;$i++) {
        if (
$char[$i]) {
         
$found = stristr($string,$char[$i]);
          if (
$found) {
           
$val = substr($string,$found+1,$len-1);
           
$string = $val;
          };
        };
      };
    } else {
     
$found = stristr($string,$char);
      if (
$found) {
       
$val = substr($string,$found+1,$len-1);
      };
    };
    echo
$val;
    return
$val;
  }

 
/*
    To use simply use the following function call:
      $color = convert_color("#FF");
      this will return the following assoc array if successful:
      *[success] = true
      *[r] = 255
      *[g] = 0
      *[b] = 0

      or copy and paste the following code:
     
      $hex = "FFFFFF"; // Color White
      $color = convert_color($hex);
      var_dump($color);
 */
?>

As you can see, the function "convert_color" accepts a hex # in most acceptable formats and returns an associative array.  [success] is set to TRUE if the function succeeds and FALSE if not.  The array members [r], [g] and [b] hold the red,green and blue values respectively.  If it fails, [error] holds a custom error message.

"strip_chars" is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function.  It will accept either a single value or an array of values for the characters to remove.
groobo 10-Feb-2005 08:46
It's just a revision to marfastic's ligten_up script, it simply adds/subtracts mod_color to orig_color.
I use it often to adjust tonals rather than brightness only

<?
function mod_color($orig_color, $mod, $mod_color){
    /*
        $orig_color - original html color, hex
        $mod_color - modifying color, hex
        $mod - modifier '+' or '-'
        usage: mod_color('CCCCCC', '+', '000033')
    */
    // does quick validation
    preg_match("/([0-9]|[A-F]){6}/i",$orig_color,$orig_arr);
    preg_match("/([0-9]|[A-F]){6}/i",$mod_color,$mod_arr);
    if ($orig_arr[0] && $mod_arr[0]) {
        for ($i=0; $i<6; $i=$i+2) {
            $orig_x = substr($orig_arr[0],$i,2);
            $mod_x = substr($mod_arr[0],$i,2);
            if ($mod == '+') { $new_x = hexdec($orig_x) + hexdec($mod_x); }
            else { $new_x = hexdec($orig_x) - hexdec($mod_x); }
            if ($new_x < 0) { $new_x = 0; }
            else if ($new_x > 255) { $new_x = 255; };
            $new_x = dechex($new_x);
            $ret .= $new_x;
        }
        return $ret;
    } else { return false; }
}
?>
19-Jan-2005 06:33
I wondered long time what is the best way to generate RGB-color from HEX-color, and just now i found the simpliest way!

<?php
$hex
= "FF00FF";
$rgb = hexdec($hex); // 16711935
?>

I hope this will save your time! :)
andreas.schmeiler 05-Feb-2003 02:59
Here's another hex2bin variant, works pretty well to me.

function hex2bin($hexdata) {
  
   for ($i=0;$i<strlen($hexdata);$i+=2) {
      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
   }
  
   return $bindata;
}
chrism at four dot net 15-Dec-2001 07:02
hexdec from 4.1.0 onwards does not show
the same size limitation and therefore
works differently with large numbers than previous php versions.

To obtain the same results, use:

(int) hexdec (...)