search for in the

 Last updated: Fri, 17 May 2013

# dechex

(PHP 4, PHP 5)

### Beschreibung

string dechex ( int `\$number` )

Konvertiert einen Wert `number` in eine hexadezimale Stringdarstellung. Der größte konvertierbare Wert ist 4294967295 (dezimal) bwz. "ffffffff" (hexadezimal).

### Parameter-Liste

`number`

Der umzuwandelnde Wert

### Rückgabewerte

Die hexadezimale Stringdarstellung von `number`

### Beispiele

Beispiel #1 dechex() Beispiel

``` <?phpecho dechex(10) . "\n";echo dechex(47);?> ```

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

```a
2f
```

### Siehe auch

• hexdec() - Hexadezimal zu Dezimal Umwandlung
• decbin() - Dezimal zu Binär Konvertierung
• decoct() - Dezimal zu Oktal Umwandlung
• base_convert() - Konvertiert einen numerischen Wert zwischen verschiedenen Zahlensystemen

 Last updated: Fri, 17 May 2013

User Contributed Notes dechex - [42 notes]
10
brent
6 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. ```
andries at centim dot be
1 year 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 ```
8 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 ```
joost at bingopaleis dot com
11 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> ```
user399026 at gmx dot com
11 months ago
``` Please note, that this function does not always output a multiple of 2 characters (dechex(10) => "a"). Use str_pad() to fill with "0"s before, if needed. It would be a good idea if PHP could add an optional parameter for this in the future. ```
sneskid at hotmail dot com
1 year 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() ```
jbleau at gmail dot com
4 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; } ?> ```
jrisken at mn dot rr dot com
7 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)); } ?> ```
Anonymous
8 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. ```
mountarreat at gmail dot com
5 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); } ?> ```
morten at nilsen dot com
8 years ago
``` I see a lot of less-than-optimal functions posted on this page, so I feel I have to give some better examples... due to the sheer size of this collection, I have made it available on my server, rather than copy/paste it into these comments. http://ryo-ohki.4th-age.com/demos/able.php and http://ryo-ohki.4th-age.com/demos/able.phps dechex replacement function from above source: <?php   define('BIT_BYTE', 8); // bits per byte   define('HEX_BYTE', BIT_BYTE/4); // hex digits in a byte   define('BIT_INT',  32); // sizeof(int)   define('HEX_INT',  BIT_INT / (BIT_BYTE/HEX_BYTE)); // hex digits in an int   function i2h(\$int, \$group=HEX_BYTE, \$size=HEX_INT, \$sep=' ') {     \$ret = '';     while(\$size--) {       \$n=(\$int>>(\$size*4)) & 0xf;       \$ret .= \$n>9?chr(55 + \$n):\$n;       if(\$size && \$size%\$group == 0) \$ret .= \$sep;     }     return \$ret;   }   echo i2h(rand(1,2)==1?-mt_rand():mt_rand()); ?> ```
mina86 at tlen dot pl
9 years ago
``` Easiest :P way to create random hex color: <?php function rand_color() {     return substr('00000' . dechex(mt_rand(0, 0xffffff)), -6); } ?> ```
huda m elmatsani <justhuda at netscape dot net>
9 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 ;) ```
mailderemi at gmail dot com
5 months ago
``` Javascript Crypt: <?php function jsCrypt(\$script,\$level=1){     for (\$j=0;\$j<\$level;\$j++){         \$asc='';         for (\$i=0;\$i<strlen(\$script);\$i++)             \$asc.='%'.dechex(ord(\$script[\$i]));         \$script='<SCRIPT LANGUAGE="JavaScript">document.write(unescape(\''.\$asc.'\'));</SCRIPT>';     }     return \$script; } echo jsCrypt('<script>alert(123);</script>',1); ?> ```
7 months ago
``` I wrote this to convert hex into signed int, hope this helps someone out there... peace :) <?php \$hex = dechex(-32767); \$dec = shexdex(\$hex); function shexdex(\$hex){     \$dec = hexdec(\$hex);         // Negative number (in binary if the msb is 1 then it is neg)     // since one hex is 4bits, the value 8 and up contain msb of 1, hence negative number        if (\$hex[0] >= '8'){    // Note: if you use the digit 8 it is not the same as '8'         \$dec -= 1;         \$dec = ~\$dec;                 return -\$dec;     }         return \$dec; } if (\$dec == -32767){     echo 'Yay!'; } ?> ```
huangwen77 at gmail dot com
11 months ago
``` For those who are looking for a function to calculate the hex of ANY length integer, here is my snippet. [It will handle] ANY length dec-to-hex conversion. The function take a string input and return a hex which is represented by a string. Note that I assumed that the user's input is a valid number thus I did NOT include any input verifying mechanism. So you have to do the verifying part yourself. <?php     // ==================== Support functions ====================     // The backoff function during contention     function backoff()     {         \$miliSeconds = rand(0, 100);         //Sleep for 0 - 100 miliseconds, to avoid collision         usleep(round(\$miliSeconds*1000));     }         // Replace a Setting in the ini     // bool set_ini(string \$old_filename, string \$new_filename)     // \$old_filename = The old log file name     // \$new_filename = the new log file name     function set_ini(\$old_filename, \$new_filename)     {         // Open the file for writing         \$fp = fopen('feedback_server.ini', 'c+');         \$canWrite = false;         //Waiting until file is locked for writing         while (!\$canWrite)         {             \$canWrite = flock(\$fp, LOCK_EX);             backoff();         }         \$content = fread(\$fp, filesize('feedback_server.ini'));         \$new_content = str_replace(\$old_filename, \$new_filename, \$content);         ftruncate(\$fp, 0);         fseek(\$fp, SEEK_SET);         fwrite(\$fp, \$new_content);         fclose(\$fp);     }     // The function to convert ANY integers to hex     // We use it in the script to convert 64-bit integer to hex     // Input: Decimal string     // Output: Hex string     // ******** In this function we pad zeros in front of the result hex to represent the number as 64-bits     function dec2hex(\$str)     {         \$hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');         // Result value         \$hexval = '';         // The quotient of each division operation         \$quotient = \$str;         \$divisor = \$str;         // The ending condition         \$flag = true;         while(\$flag)         {             \$len = strlen(\$divisor);             \$pos = 1;             \$quotient = 0;             // Take the first two digits as temp divisor and advance by 1 each iteration             \$div = substr(\$divisor, 0, 2);             \$remainder = \$div[0];             while(\$pos < \$len)             {                 // Calculate the next div                 \$div = \$remainder == 0 ? \$divisor[\$pos] : \$remainder.\$divisor[\$pos];                 \$remainder = \$div % 16;                 \$quotient = \$quotient.floor(\$div/16);                 \$pos++;             }             // Recast the divisor as string to make the \$divisor[\$pos] work             \$quotient = trim_left_zeros(\$quotient);             \$divisor = "\$quotient";             \$hexval = \$hex[\$remainder].\$hexval;             // If the divisor is smaller than 15 then end the iteration             if (strlen(\$divisor)<=2)             {                 if (\$divisor<15)                 {                     \$flag = false;                 }             }         }         \$hexval = \$hex[\$quotient].\$hexval;         \$hexval = trim_left_zeros(\$hexval);         // Pad zeros (only because we are using this function for 64-bit integers)         //\$hexval = str_repeat('0', 16-strlen(\$hexval)).\$hexval;         return \$hexval;     }     // Trim the zeros at the left of a number     function trim_left_zeros(\$str)     {         \$str = ltrim(\$str, '0');         if (empty(\$str))         {             \$str = '0';         }         return \$str;     } ?> ```
9381904 at gmail dot com
1 year ago
``` for mac address <?php function dec2mac(\$mac) {    \$mac=preg_split("([.])", \$mac, 6);    \$hexmac="";    foreach (\$mac as \$part)    {    \$part=dechex(\$part);    strlen(\$part)<2 ? \$hexmac.="0\$part" : \$hexmac.=\$part;    }    return \$hexmac; } echo dec2mac("0.29.96.71.60.137"); // 001d60473c89 ?> ```
Mista-NiceGuy at web dot de
7 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")); ?> ```
cory at lavacube dot com
7 years ago
``` 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. :-) ```
michael at m-ganzer dot de
7 years ago
``` simple, non-recursive way of zerofilling (why making everything complicated, there r more than enough inbuilt functions) function zfill(\$n,\$a) {   return str_repeat("0",max(0,\$a-strlen(\$n))).\$n; } "max(0,..." as multiplier inside of "str-repeat" is preventing an error with negative values, if the string length was already higher than the accuracy parameter for zfill. have fun! :) ```
oliver at realtsp dot com
7 years ago
``` Warning for use on 64 bit machines! The Extra length matters! 32bit machine: php -r 'echo dechex(4294967295);' output: ffffffff 64bit machine: php -r 'echo dechex(4294967295);' output: ffffffff so far it is ok. But for slightly bigger numbers: 32bit machine: php -r 'echo dechex(4294967296);' output: 0 64bit machine: php -r 'echo dechex(4294967296);' output: 100000000 note the difference! This is particularly important when converting negative numbers: 64bit machine: php -r 'echo dechex(-1);' output: ffffffffffffffff 32bit machine: php -r 'echo dechex(-1);' output: ffffffff If you want your code to be portable to amd64 or xeons (which are now quite popular with hosting companies) then you must ensure that your code copes with the different length of the result for negative numbers (and the max value, although that is probably less critical). ```
matt dot smith at email dot ky
8 years ago
``` It took me hours, but I've finally figured it all out... -- To figure up how many lines it'll take to get from, 0000 to FFFF, use this formula: ((hex_length / 2) * 255) + 1 For 0000 to FFFF, this would be: ((4 / 2) * 255) + 1 = 511 For 0000000000 to FFFFFFFFFF, this would be: ((10 / 2) * 255) + 1 = 1276 -- To figure up how many possibilities a certain hex length will give (such as that of an MD5 hash, for example), use this formula: 256^(hex_length / 2) Like so: hex = 0123ABCDEF hex_length = 10 possibilities = 256^(10 / 2) possibilities = 256^5 possibilities = 1,099,511,627,776 -- And I don't know how useful this next part is, but it's quite nifty. Just set \$length to be your hex_length and it'll display all "incrementally-possible" hexadecimals, along with line numbers: <?php \$length = 10; // Change this to the total length of your hexadecimal function array_check(\$array1, \$array2) {     \$count1 = count(\$array1);     \$count2 = count(\$array2);         if (\$count1 != \$count2)         return FALSE;         \$match = 0;     for (\$i = 0; \$i < \$count1; \$i++)         if (\$array1[\$i] == \$array2[\$i])             \$match++;         if (\$match != \$count1)         return FALSE;         return TRUE; } function zeropad(\$num) {     return (strlen(\$num) == 1) ? '0'.\$num : \$num; } function zeropad_lineno(\$num, \$length) {     while (strlen(\$num) < \$length)         \$num = '0'.\$num;         return \$num; } \$hexadecimals = \$length / 2; \$possibilities = /*number_format(*/ pow(256, \$hexadecimals) /*)*/; echo "A hexadecimal of this length ({\$length}) has {\$possibilities} possibilities.<br>\n"; echo "<br>\n"; //init for (\$i = 0; \$i < \$hexadecimals; \$i++) {     \$x[] = '00';     \$xint[] = 0;         \$end[] = 'ff'; } \$line = 0; while ( !(array_check(\$x, \$end)) ) // while we're not currently at the end (FF..) {     \$hexstr = '';     for (\$i = 0; \$i < \$hexadecimals; \$i++)     {         \$x[\$i] = dechex(\$xint[\$i]);         \$hexstr .= zeropad(dechex(\$xint[\$i]));     }         \$line++;     \$linestr = zeropad_lineno(\$line, 8);     echo "<code>{\$linestr}: {\$hexstr}</code><br>\n";         // hex increment     for (\$i = (\$hexadecimals - 1); \$i >= 0; \$i--)     {         // increment bit if possible         if (\$xint[\$i] != 255)         {             // increment bit and then break out of the for loop             \$xint[\$i]++;             break;         }     } } ?> ```
wangster at darkcore dot net
8 years ago
``` This function will take a string and convert it into a hexdump. e.g. 3c666f6e 74207369 7a653d22 33223e4c  <font.size."3">L 6561726e 20686f77 20746f20 62652061  earn.how.to.be.a function hexdump(\$string) {    \$hex="";    \$substr = "";    for (\$i=0; \$i < strlen(\$string) ;\$i++) {      if(!(\$i % 4) && \$i != 0) {        \$hex .= " ";      }      if(!(\$i % 16) && \$i != 0) {        \$clean = preg_replace("/[^a-zA-Z0-9!-.<>\/]/",".",\$substr);        \$hex .= " ".htmlentities(\$clean)."\n";        \$substr = "";      }      \$substr .=  \$string[\$i];      \$hex .= dechex(ord(\$string[\$i]));    }    return \$hex; } ```
admin[TAKETHISOUT] at torsoft dot no-ip dot com
9 years ago
``` <?php /* here are two functions, some might find them useful (maybe for encoding) converting string to hex and hex to string: */ function strhex(\$string) {     \$hex="";     for (\$i=0;\$i<strlen(\$string);\$i++)         \$hex.=(strlen(dechex(ord(\$string[\$i])))<2)? "0".dechex(ord(\$string[\$i])): dechex(ord(\$string[\$i]));     return \$hex; } function hexstr(\$hex) {     \$string="";     for (\$i=0;\$i<strlen(\$hex)-1;\$i+=2)         \$string.=chr(hexdec(\$hex[\$i].\$hex[\$i+1]));     return \$string; } ?> ```
daevid at daevid dot com
9 years ago
``` Here's my version of a red->yellow->green gradient: <?php function colorMeter(\$percent, \$invert = false) {     //\$percent is in the range 0.0 <= percent <= 1.0     //    integers are assumed to be 0% - 100%              // and are converted to a float 0.0 - 1.0     //     0.0 = red, 0.5 = yellow, 1.0 = green     //\$invert will make the color scale reversed     //     0.0 = green, 0.5 = yellow, 1.0 = red         //convert (int)% values to (float)     if (is_int(\$percent)) \$percent = \$percent * 0.01;         \$R = min((2.0 * (1.0-\$percent)), 1.0) * 255.0;     \$G = min((2.0 * \$percent), 1.0) * 255.0;     \$B = 0.0;         return ((\$invert) ? sprintf("%02X%02X%02X",\$G,\$R,\$B) : sprintf("%02X%02X%02X",\$R,\$G,\$B)); } //colorMeter ?> and use it like this: <TABLE BORDER=1 WIDTH="300"> <?php for (\$i = 0.0; \$i <= 1.0; \$i += 0.10) {     \$RGB = colorMeter(\$i);     print "<TR><TD BGCOLOR='".\$RGB."'>".\$i."</TD><TD> <PRE>".\$RGB."</PRE></TD></TR>\n"; } ?> </TABLE> <P> <TABLE BORDER=1 WIDTH="300"> <?php for (\$i = 0; \$i <= 100; \$i += 10) {     \$RGB = colorMeter(intval(\$i), true);     print "<TR><TD BGCOLOR='".\$RGB."'>".\$i."</TD><TD> <PRE>".\$RGB."</PRE></TD></TR>\n"; } ?> </TABLE> ```
thr at recide dot net
9 years ago
``` /* * RGB-Colorcodes(i.e: 255 0 255) to HEX-Colorcodes (i.e: FF00FF) */ function rgb2hex(\$rgb){     if(!is_array(\$rgb) || count(\$rgb) != 3){         echo "Argument must be an array with 3 integer elements";         return false;     }     for(\$i=0;\$i<count(\$rgb);\$i++){         if(strlen(\$hex[\$i] = dechex(\$rgb[\$i])) == 1){             \$hex[\$i] = "0".\$hex[\$i];         }     }     return \$hex; } /* Example */ print_r(rgb2hex(array(10,255,255))); ```
m0sh3 at hotmail dot com
9 years ago
``` This will can convert decimal of more than 2^48 in any PHP version: \$hex = dechex(\$dec>>24).dechex(\$dec & 0xFFFFFF) ```
allan-wegan at allan-wegan dot de
9 years ago
``` now, here is a nice and small function to convert integers to hex strings and it avoids use of the DECHEX funtion because that function changed it's behavior too often in the past (now, in PHP version 4.3.2 it works with numbers bigger than 0x7FFFFFFF correctly, but i need to be backward compatible). function &formatIntegerForOutput(\$value) {     \$text = "00000000";     \$transString = "0123456789ABCDEF";     // handle highest nibble (nibble 7):         \$nibble = \$value & 0x70000000;         \$nibble >>= 28;         if (\$value < 0) {             \$nibble = \$nibble | 0x00000008;         }         \$text[0] = \$transString[\$nibble];         \$value &= 0x0FFFFFFF;     // nibbles 0 to 6:         for (\$a = 7; \$a > 0; \$a --) {             \$nibble = \$value & 0x0000000F;             \$text[\$a] = \$transString[\$nibble];             \$value >>= 4;         }     return \$text } this function should be not too slow and is really simple. I don't know, if the DECHEX function in the future will pad it's output to ever be 8 characters in length - so for backward compatibility reasons even in future PHP versions i avoided to use it. ```
monkyNOSPAM at phpfi dot org dot invalid
10 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); ```
jfren484 at hotmail dot com
11 years ago
``` Here's a function which works for decimal values up to 9007199254740992 (hex 20000000000000). function dec2hex(\$dec) {   \$hex = (\$dec == 0 ? '0' : '');   while (\$dec > 0)   {     \$hex = dechex(\$dec - floor(\$dec / 16) * 16) . \$hex;     \$dec = floor(\$dec / 16);   }   return \$hex; } ```
kristoffer at caveo dot se
11 years ago
``` Heres a example of dec to html hex gradient. Have fun :) //Amount of gradients \$l = 20; //Start color \$start[0] = "255";     //red \$start[1] = "0";     //green \$start[2] = "255";     //blue //End color \$end[0] = "255";     //red \$end[1] = "255";    //green \$end[2] = "255";    //blue for (\$t = 1; \$t < \$l;) {     \$x = \$x * \$t;     for (\$i = 0; \$i < 3;) {         \$buffer[\$i] = \$start[\$i] - \$end[\$i];         \$buffer[\$i] = floor(\$buffer[\$i] / \$l);         \$rgb[\$i] = \$start[\$i] - (\$buffer[\$i] * \$t);         if (\$rgb[\$i] > 255) {             \$rgb[\$i] = 255;         }         \$rgb[\$i] = dechex(\$rgb[\$i]);         \$rgb[\$i] = strtoupper(\$rgb[\$i]);         if (strlen(\$rgb[\$i]) < 2) {             \$rgb[\$i] = "0\$rgb[\$i]";         }         \$i++;     }     \$color = "\$rgb[0]\$rgb[1]\$rgb[2]";     echo "\$color";         \$t++; } ?> ```
-1
sjaak at spoilerfreaks dot com
6 years ago
``` To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them. for example <?php echo(dechex("2724838310")); ?> will print '7FFFFFFF' but it should print 'A269BBA6' When adding '+0' php will handle the 32bit unsigned integer correctly <?php echo(dechex("2724838310"+0)); ?> will print 'A269BBA6' ```
-1
foros at basnek dot com
6 years ago
``` I leave code blocks them that I have made to be able to replace the content of certain blocks of JS that used eval () I hope serves to them. <?php // Convert hex 2 str // Imput Example: \x68\x6f\x6c\x61\x20\x6d\x75\x6e\x64\x6f \$que=( isset( \$_POST['hexadecimal'] ) )?\$_POST['hexadecimal']:""; \$valores=explode( "\\\x", \$que ); for ( \$i=0; \$i<count( \$valores ) ; \$i++) {     echo chr(  hexdec( \$valores[\$i] ) ) ; } // Convert str 2 hex // Imput Example: hola mundo \$que=( isset( \$_POST['ascii'] ) )?\$_POST['ascii']:""; for ( \$i=0; \$i<strlen( \$que ) ; \$i++) {     echo "\\x".dechex( ord( substr( \$que, \$i, 1) ) ) ; } ?> ```
-1
trance4rm
7 years ago
``` a bugfix for admin AT bobfrank DOT org' s post The original was: <?php function zeropad(\$num, \$lim) {    return (strlen(\$num) >= \$lim) ? \$num : zeropad("0" . \$num); } ?> I couldn't get it to work, kept getting a "Missing argument 2 for zeropad()" error, even though I called the function with both arguments -- then I noticed the recursive part, and the missing \$lim argument.  The code that works is: <?php function zeropad(\$num, \$lim) {    return (strlen(\$num) >= \$lim) ? \$num : zeropad("0" . \$num, \$lim);     // \$lim was missing from the recursive call // the function will prefix \$num with a zero and recursively call itself // each recursive call, \$num gets one digit bigger until strlen of \$num  equals \$lim } ?> ```
-1
manithu
8 years ago
``` If you want to fade some text from one color to another, use this function: <?php function colorFade(\$text, \$color1, \$color2, \$HTMLelement = 'span') {     //remove leading and trailing whitespaces.     \$text = trim(\$text);         //split the characters of the text to an array.     \$char = array();     for (\$i = 0; \$i < strlen(\$text); \$i++) {         \$char[\$i] = substr(\$text, \$i, 1);     }     //convert the hexadecimal colors in decimal.     \$decimalColor = array();     //first color     \$decimalColor[0] = hexdec(substr(\$color1, 0, 2));     \$decimalColor[1] = hexdec(substr(\$color1, 2, 2));     \$decimalColor[2] = hexdec(substr(\$color1, 4, 2));     //second color     \$decimalColor[3] = hexdec(substr(\$color2, 0, 2));     \$decimalColor[4] = hexdec(substr(\$color2, 2, 2));     \$decimalColor[5] = hexdec(substr(\$color2, 4, 2));         //formated chars are stored here (the key 0 is for the first     //char and must not be removed).     \$newText = array(0 => null);     //run over every character except the first and the last,     //they will be added later.     for (\$i = 2; \$i <= strlen(\$text)-1; \$i++) {         //check if the character is only a whitespace. If yes,         //save the whitespace without adding color and proceed         //to the next character.         if (!trim(\$char[\$i-1])) {             \$newText[] = \$char[\$i-1];             continue;         }         //calculate the (hex) color for this character.         \$color = array();         //red         \$color[] = dechex((\$decimalColor[0] - \$decimalColor[3])                    / strlen(\$text) * \$i + \$decimalColor[3]);         //green         \$color[] = dechex((\$decimalColor[1] - \$decimalColor[4])                    / strlen(\$text) * \$i + \$decimalColor[4]);         //blue         \$color[] = dechex((\$decimalColor[2] - \$decimalColor[5])                    / strlen(\$text) * \$i + \$decimalColor[5]);                 //check if every color part is 2 chars long, if not, repeat it.         foreach (\$color as \$k => \$v) {             if (strlen(\$v) < 2) {                 \$color[\$k] = str_repeat(\$v, 2);             }         }         //merge the parts to the full hex color.         \$color = implode(\$color, '');                 //Save the formated char.         \$newText[] = '<'.\$HTMLelement.' style="color:#'.\$color.'">'.                      \$char[\$i-1].'</'.\$HTMLelement.'>';     }     //add first char.     \$newText[0] = '<'.\$HTMLelement.' style="color:#'.\$color2.'">'.                   \$char[0].'</'.\$HTMLelement.'>';     //add last char.     \$newText[]  = '<'.\$HTMLelement.' style="color:#'.\$color1.'">'.                   \$char[strlen(\$text)-1].'</'.\$HTMLelement.'>';         //merge the characters and return it.     return implode(\$newText, ''); } ?> \$color1 is the start color, \$color2 the end color. I hope this helps somebody. ```
-1
Anonymous
8 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 ?> ```
-1
paeppi at actionorg dot de
9 years ago
``` Easier way to create random hex color: <?php function rand_color() {     \$hexcolor = dechex(mt_rand(0,16777215));     while (strlen(\$hexcolor) < 6) {         \$hexcolor = \$hexcolor."0";     }     return \$hexcolor; } echo "#".rand_color(); ?> ```
-1
paoligno at tin dot it
10 years ago
``` you can use this workaround (raw but simple and efficient) \$string=DecHex(\$string*1) bye bye ```
-1
the_tenth at pandora dot be
10 years ago
``` <? function dec2hex(\$number) { \$length=16; \$hexval=""; while (\$number>0) { \$remainder=bcmod(\$number,16); if (\$remainder<10) \$hexval=\$remainder.\$hexval; elseif (\$remainder==10) \$hexval="A".\$hexval; elseif (\$remainder==11) \$hexval="B".\$hexval; elseif (\$remainder==12) \$hexval="C".\$hexval; elseif (\$remainder==13) \$hexval="D".\$hexval; elseif (\$remainder==14) \$hexval="E".\$hexval; elseif (\$remainder==15) \$hexval="F".\$hexval; \$number=bcdiv(\$number,16); } while (strlen(\$hexval)<\$length) \$hexval="0".\$hexval; return \$hexval; } \$tmp = "<table width='643' border='1'>"; \$x = 1; \$y = 1; \$z = dec2hex(\$x); \$q = dec2hex(\$y); for (\$i=1;\$i<65;\$i++){     \$x= bcpow(2,(\$i-1));     \$z = dec2hex(\$x);     \$tmp .="<tr><td width='20' align='center' bgcolor='#808080'><font color='#ffffff'>". \$i;     \$tmp .="</font></td><td width='5'>2<sup>". (\$i-1) . "</sup></td><td width='2'>=</td></td><td>" . \$x . "</td>";     \$tmp .="<td>".\$z."</td><td>".\$y."</td><td>".\$q."</td></tr>";     \$y = bcsub(bcpow(2,\$i+1),1);     \$q = dec2hex(\$y);     } \$tmp .= "</table>"; echo \$tmp; ?> ```
-2
jpfstange at gmail dot com
2 years ago
``` <?php         /**         * String to HEX | HEX to String. Automatic detection.         * This script just takes input from the command line         * and transforms an ASCII String to HEX or viceversa.         * If you want to use it in a web page just change the \$str variable below.         * Cheers, Juan Stange.-         */         \$str = \$_SERVER["argv"][1];         function hexEncode(\$str=NULL){                 if(is_null(\$str)){                         return FALSE;                 }                 \$hexStr = "";                 for(\$i=0;isset(\$str[\$i]);\$i++){                         \$char = dechex(ord(\$str[\$i]));                         \$hexStr .= \$char;                 }                 return "0x".\$hexStr;         }         function asciiEncode(\$str=NULL){                 if(!preg_match("/^0x[A-Fa-f0-9]+/",\$str)){                         return FALSE;   //Not a hex string                 }                 \$str = substr(\$str,2);                 \$asciiString = "";                 for(\$i=0;isset(\$str[\$i]);\$i+=2){                         \$hexChar = substr(\$str,\$i,2);                         \$asciiString .= chr(hexdec(\$hexChar));                 }                 return \$asciiString;         }         \$return = (\$encoded=asciiEncode(\$str)) ? \$encoded : hexEncode(\$str);         echo \$return."\n"; ?> ```
-2
Ruben Barkow ( at web dot de)
8 years ago
``` this function generates an hex-colorcode out of a string. usefull if you want to show a list of words all in different colors, that should remain its color even if the order changes. (if the string is empty, it gives back a random color) function word2color(\$w){ if (strlen(\$w)==0) return substr('00000' . dechex(mt_rand(0, 0xffffff)), -6); while (strlen(\$w)<6) \$w.=\$w; \$minbrightness=1;  // range from 0 to 15, if this is 0 then for ex. black is allowed \$max_brightness=14; // range from 0 to 15, if this is 15 then for ex. white is allowed \$plus_red=0;    // set one of these to set the probability of one of these colors higher \$plus_green=0; \$plus_blue=0; for (\$i=0; \$i<6; \$i++) {     #\$r.= '">';// this is a depug mode, to see the color written     \$plus=0;     if (\$plus_red<>0 and \$i==0) \$plus=\$plus_red;     if (\$plus_green<>0 and \$i==2) \$plus=\$plus_green;     if (\$plus_blue<>0 and \$i==4) \$plus=\$plus_blue;     \$c=\$w[round(strlen(\$w)/6*\$i)];     \$dec=ord(\$c)%(\$max_brightness+\$plus-\$minbrightness) +\$minbrightness+\$plus;     if (\$dec>\$max_brightness-\$minbrightness) \$dec=\$max_brightness-\$minbrightness;     \$r.= strtoupper( dechex(\$dec) ); } return \$r; } ```
-2
paeppi at actionorg dot de
9 years ago
``` # One example how to convert a decimal number into any other system (here 32 digits -- 0 to v) and how to convert back. # Just replace the "32" in my functions with the number of digits in "your" system, and continue the replace-lists. # This is surely not the very best way to do this, but it hopefully helps :-) function decttw(\$int_dec) {     \$s = \$int_dec;     while (\$i < 19) {         \$exp = pow(32,18 - \$i);         \$modulo = fmod(\$s,\$exp);         \$value = (\$s - \$modulo) / \$exp;         if ((\$value > 0) && (\$start != 1)) {             \$start = 1;         }         if (\$start == 1) {             \$decs = \$value;             \$decs = ereg_replace ("10", "a", \$decs);             \$decs = ereg_replace ("11", "b", \$decs);             \$decs = ereg_replace ("12", "c", \$decs);             \$decs = ereg_replace ("13", "d", \$decs);             \$decs = ereg_replace ("14", "e", \$decs);             \$decs = ereg_replace ("15", "f", \$decs);             \$decs = ereg_replace ("16", "g", \$decs);             \$decs = ereg_replace ("17", "h", \$decs);             \$decs = ereg_replace ("18", "i", \$decs);             \$decs = ereg_replace ("19", "j", \$decs);             \$decs = ereg_replace ("20", "k", \$decs);             \$decs = ereg_replace ("21", "l", \$decs);             \$decs = ereg_replace ("22", "m", \$decs);             \$decs = ereg_replace ("23", "n", \$decs);             \$decs = ereg_replace ("24", "o", \$decs);             \$decs = ereg_replace ("25", "p", \$decs);             \$decs = ereg_replace ("26", "q", \$decs);             \$decs = ereg_replace ("27", "r", \$decs);             \$decs = ereg_replace ("28", "s", \$decs);             \$decs = ereg_replace ("29", "t", \$decs);             \$decs = ereg_replace ("30", "u", \$decs);             \$decs = ereg_replace ("31", "v", \$decs);             \$int_value = \$int_value.\$decs;         }         \$s = \$s - \$value * \$exp;         \$i++;     }     return \$int_value; } function ttwdec(\$int_ttw) {     \$digits = strlen(\$int_ttw);     while (\$i < \$digits) {         \$s = substr(\$int_ttw,\$i,1);         \$decs = \$s;         \$decs = ereg_replace ("a", "10", \$decs);         \$decs = ereg_replace ("b", "11", \$decs);         \$decs = ereg_replace ("c", "12", \$decs);         \$decs = ereg_replace ("d", "13", \$decs);         \$decs = ereg_replace ("e", "14", \$decs);         \$decs = ereg_replace ("f", "15", \$decs);         \$decs = ereg_replace ("g", "16", \$decs);         \$decs = ereg_replace ("h", "17", \$decs);         \$decs = ereg_replace ("i", "18", \$decs);         \$decs = ereg_replace ("j", "19", \$decs);         \$decs = ereg_replace ("k", "20", \$decs);         \$decs = ereg_replace ("l", "21", \$decs);         \$decs = ereg_replace ("m", "22", \$decs);         \$decs = ereg_replace ("n", "23", \$decs);         \$decs = ereg_replace ("o", "24", \$decs);         \$decs = ereg_replace ("p", "25", \$decs);         \$decs = ereg_replace ("q", "26", \$decs);         \$decs = ereg_replace ("r", "27", \$decs);         \$decs = ereg_replace ("s", "28", \$decs);         \$decs = ereg_replace ("t", "29", \$decs);         \$decs = ereg_replace ("u", "30", \$decs);         \$decs = ereg_replace ("v", "31", \$decs);         \$i++;         \$value = \$decs * pow(32,(\$digits - \$i));         \$int_value = \$int_value + \$value;     }     return \$int_value; } ```