Php string to hex number

I have a string that looks like this "7a" and I want to convert it to the hex number 7A. I have tried using pack and unpack but that is giving me the hex representation for each individual character.

asked May 19, 2010 at 14:43

cskwrdcskwrd

2,6937 gold badges36 silver badges49 bronze badges

Probably the simplest way to store that as an integer is hexdec[]

$num = hexdec[ '7A' ];

answered May 19, 2010 at 14:46

Peter BaileyPeter Bailey

104k31 gold badges180 silver badges201 bronze badges

3

Well a number is a number, it does not depend on the representation. You can get the actual value using intval[]:

$number = intval['7a', 16]; 

To convert the number back to a hexadecimal string you can use dechex[].

answered May 19, 2010 at 14:48

Felix KlingFelix Kling

767k171 gold badges1067 silver badges1114 bronze badges

This can by try -

function strToHex[$string]
{
$hex='';
for [$i=0; $i < strlen[$string]; $i++]
{
    $hex .= dechex[ord[$string[$i]]];
}
return $hex;
}

answered Dec 22, 2012 at 7:37

aforankuraforankur

1,2911 gold badge15 silver badges27 bronze badges

1

Not the answer you're looking for? Browse other questions tagged php string hex or ask your own question.

[PHP 4, PHP 5, PHP 7, PHP 8]

dechexDecimal to hexadecimal

Description

dechex[int $num]: string

The largest number that can be converted is PHP_INT_MAX * 2 + 1 [or -1]: on 32-bit platforms, this will be 4294967295 in decimal, which results in dechex[] returning ffffffff.

Parameters

num

The decimal value to convert.

As PHP's int type is signed, but dechex[] deals with unsigned integers, negative integers will be treated as though they were unsigned.

Return Values

Hexadecimal string representation of num.

Examples

Example #1 dechex[] example

The above example will output:

Example #2 dechex[] example with large integers

The above example will output:

ffffffff
ffffffff
ffffffff

See Also

  • hexdec[] - Hexadecimal to decimal
  • decbin[] - Decimal to binary
  • decoct[] - Decimal to octal
  • base_convert[] - Convert a number between arbitrary bases

brent

15 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.

joost at bingopaleis dot com

20 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.


// 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;
}

jrisken at mn dot rr dot com

17 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:

admin AT bobfrank DOT org

17 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

mina86 at tlen dot pl

18 years ago

Easiest :P way to create random hex color:

mountarreat at gmail dot com

14 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!

Anonymous

17 years ago

If you need to generate random HEX-color, use this:


Enjoy.

jbleau at gmail dot com

13 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.

allan-wegan at allan-wegan dot de

19 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

19 years ago

Here's how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by above.

function hexColor[$color] {
  return dechex[[$color[0]

huda m elmatsani

18 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 ;]

andries at centim dot be

10 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

mahdiyari

1 month ago

Zero padded hex strings as a pair of 2 [8bit].

hugo

5 years ago

warning jbleau dec_to_hex method is buggy, avoid it.

dec_to_hex['9900000397']-->24e16048f
dec_to_hex['9900000398']-->24e16048f
dec_to_hex['9900000399']-->24e16048f

mailderemi at gmail dot com

9 years ago

Javascript Crypt:

delchodimi at gmail dot com

7 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]

hmlinks at gmail dot com

9 years ago

I wrote this to convert hex into signed int, hope this helps someone out there... peace :]

sneskid at hotmail dot com

10 years ago

If you want to create or parse signed Hex values:



Also note that ['0x' . $str + 0] is faster than hexdec[]

sjaak at spoilerfreaks dot com

15 years ago

To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example

will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly

will print 'A269BBA6'

Mista-NiceGuy at web dot de

16 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.

9381904 at gmail dot com

10 years ago

for mac address

oliver at realtsp dot com

17 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].

wangster at darkcore dot net

17 years ago

This function will take a string and convert it into a hexdump.

e.g.

3c666f6e 74207369 7a653d22 33223e4c  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;
}

daevid at daevid dot com

18 years ago

Here's my version of a red->yellow->green gradient:



and use it like this:


Chủ Đề