How do you assign a hexadecimal number as the value to a variable in php?

I am trying to represent a character by its hex value inside a string. It works if hex is explicit but does not work when hex variable is used:

$hex = '5A';
echo "Hex explicit: \x5A, Hex evaluated: \x$hex";

The output is:

Hex explicit: Z, Hex evaluated: \x5A

The question is - how do I modify \x$hex to get Z instead of \x5A?

asked Sep 4, 2013 at 5:00

Dmitri ZaitsevDmitri Zaitsev

13k10 gold badges71 silver badges107 bronze badges

Hope this helps.

Integer literals

 

This is the answer

$hex = chr[0x5A];
echo "Hex explicit: \x5A, Hex evaluated:".$hex;

or

$hex = chr[0x5A];
echo "Hex explicit: \x5A, Hex evaluated: $hex";

Try this link //www.w3schools.com/php/func_string_chr.asp

answered Sep 4, 2013 at 5:08

Harsha JayamannaHarsha Jayamanna

2,0604 gold badges23 silver badges40 bronze badges

6

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

hexdecHexadecimal to decimal

Description

hexdec[string $hex_string]: int|float

hexdec[] will ignore any non-hexadecimal characters it encounters. As of PHP 7.4.0 supplying any invalid characters is deprecated.

Parameters

hex_string

The hexadecimal string to convert

Return Values

The decimal representation of hex_string

Changelog

VersionDescription
7.4.0 Passing invalid characters will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist.

Examples

Example #1 hexdec[] example

Notes

Note:

The function can convert numbers that are too large to fit into the platforms int type, larger values are returned as float in that case.

See Also

  • dechex[] - Decimal to hexadecimal
  • bindec[] - Binary to decimal
  • octdec[] - Octal to decimal
  • base_convert[] - Convert a number between arbitrary bases

hafees at msn dot com

12 years ago

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



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

programacion at mundosica dot com

10 years ago

Here is other function to transform a MAC Address to decimal:

flurinj at gmx dot net

12 years ago

Here My version of converting a hex string to a signed decimal value:

brian at sagesport dot com

17 years ago

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.



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.

chuckySTAR

13 years ago

Here's my hexdec function for greater numbers using BC Math

k10206 at naver dot com

14 years ago

Halit YEL - halityesil at globya dot net

12 years ago

RGB to Hex
Hex to RGB
Function



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

Anonymous

17 years ago

I wondered long time what is the best way to generate RGB-color from HEX-color, and just now i found the simpliest way!



I hope this will save your time! :]

Walter Wlodarski

14 years ago

One of my favourite, multi-purpose, bidirectional solution I wrote many years ago:

function bgr2rgb[$cr] {  // bidirectional
    return [[$cr & 0x0000FF] > 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]; }

sneskid at hotmail dot com

10 years ago

If you want to create or parse signed Hex strings:



Also note that ['0x' . $hexstr + 0] is faster than hexdec[]
[Tested on PHP v5.2.17]

jose dot rob dot jr at gmail dot com

13 years ago

I made these functions to pack up to 64 ID's into a mysql unsigned bigint.

ID's cannot repeat, must be

Have fun ;D

Ultimater at gmail dot com

13 years ago

hexdec doesn't accept numbers following the period.
What if you have a number like c20.db18?

helpmedalph at gmail dot com

6 years ago

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

chrism at four dot net

20 years ago

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

joquius at kakugo dot com

14 years ago

Help a hex-stricken string get back to normal:

Anonymous

14 years ago

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

Manithu

15 years ago

This tiny function will return foreground colors [either black or white] in contrast to the color you provide:



This function will return the opposite [negative]:

cgarvis at gmail dot com

15 years ago

Here is my version of hex2rgb for web colors to 24bit colors.

repley at freemail dot it

16 years ago

From color to color to ...... to color with fade effect. Good for dynamic bar chart.



Repley.

cory at lavacube dot com

16 years ago

A handy little function to convert HEX colour codes to "web safe" colours...



Example: color_mkwebsafe['0e5c94'];
Produces: 006699

Hope this helps someone out... Happy coding. :-]

detrate at hotmail dot com

16 years ago

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

Gabriel Reguly

17 years ago

After esnhexdec from "rledger at gmail dot com",  the esndechex:

bishop

17 years ago

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:



Handles 2, 3, and 6 character colour codes with leading # or &H.

zubfatal, root at it dot dk

17 years ago

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.

groobo

17 years ago

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

this1is4me at hotmail dot com

14 years ago

In reply to Amit Yadav's post [hex to binary conversion]:

function binfromdec[$num]
{
  $primary = "bit";
  for [$i=1; $i

Rosberg - rosberglinhares at gmail dot com

12 years ago

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

How do you assign a hex value to a variable?

To assign value in hexadecimal format to a variable, we use 0x or 0X suffix. It tells to the compiler that the value [suffixed with 0x or 0X] is a hexadecimal value and assigns it to the variable.

How do you declare an integer variable in PHP?

There are a few ways to do so:.
Cast the strings to numeric primitive data types: $num = [int] "10"; $num = [double] "10.12"; // same as [float] "10.12";.
Perform math operations on the strings: $num = "10" + 1; $num = floor["10.1"];.
Use intval[] or floatval[] : ... .
Use settype[] ..

What is Hexdec PHP?

Definition and Usage The hexdec[] function converts a hexadecimal number to a decimal number. Tip: To convert decimal to hexadecimal, look at the dechex[] function.

How do you declare a hex variable in Python?

When denoting hexadecimal numbers in Python, prefix the numbers with '0x'. Also, use the hex[] function to convert values to hexadecimal format for display purposes.

Chủ Đề