Dusty
Dusty

Reputation: 125

php, convert to hexadecimal integer

My $_POST value contains css friendly hex color value, for example: #ffffff. In order to make it friendly towards the ColorJizz library, I should have it in hexadecimal integer value. The code below doesn't work. If I replace the $color_hex variable with a hard coded value for example: 0xffffff, it works.

include('colorjizz.php');   
$color_hex = '0x' . substr($_POST['color'], 1); 
$color = new Hex($color_hex);

This is most likely a very noob level problem, but after hitting my head to the wall for a quite few hours, I'd be grateful for any advice. Thank you.

Upvotes: 2

Views: 2962

Answers (3)

Eliasdx
Eliasdx

Reputation: 2180

If you have a string containing a hexadecimal representation of a number and you want to have it as a integer you have to convert from hex to dec. If I get your question right.

$dec = hexdec("ff0000");

http://php.net/hexdec

Upvotes: 1

ikegami
ikegami

Reputation: 385506

"Hexadecimal integer value" doesn't make much sense. Hex is a representation of a number (thus a string), while integer value speaks of the machine format of a number.

If you want the number, a quick Google search found hexdec

$color = hexdec(substr($_POST['color'], 1));

It appears to ignore leading "junk", so you could even use

$color = hexdec($_POST['color']);

Upvotes: 2

Lucas Jones
Lucas Jones

Reputation: 20183

In PHP, the data type for a hexadecimal integer and a decimal integer is the same; being able to type 0xDEAD in your source code is just syntactic sugar. Thus, you can use intval() to convert the form input to a normal PHP integer from a string:

$color_hex = intval(substr($_POST['color'], 1), 16);

The final parameter, 16, specifies that the input string is in hexadecimal.

Upvotes: 0

Related Questions