Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert hexadecimal values to decimal values
function convert_hex2dec($hex) {
// Remove hashmark, if present.
if (substr($hex, 0, 1) === '#') {
$hex = substr($hex, 1);
}
// Max of 8 characters.
if (strlen($hex) > 8) {
$hex = substr($hex, 0, 8);
}
// Count the characters.
$length = strlen($hex);
// Get hex as an array.
$chars = str_split($hex);
// Handle 3-digit hexes; convert to 6-digit counterparts.
if ($length === 3) {
$hex = $chars[0].$chars[0].$chars[1].$chars[1].$chars[2].$chars[2];
}
// Handle non-6-digit hexes; convert to 6-digit by padding with zero(s).
if ($length !== 6) {
$hex = str_pad($hex, 6, '0');
$chars = str_split($hex);
}
// Handle (or append) alpha value.
if (count($chars) === 6) {
$chars[] = 'f';
$chars[] = 'f';
} else if (count($chars) === 7) {
$chars[] = $chars[6];
}
// Initialization.
$values = [];
// RGB values.
$values['rgb_r'] = hexdec($chars[0].$chars[1]);
$values['rgb_g'] = hexdec($chars[2].$chars[3]);
$values['rgb_b'] = hexdec($chars[4].$chars[5]);
$values['rgb_a'] = hexdec($chars[6].$chars[7]);
// HEX values.
$values['hex_r'] = $chars[0].$chars[1];
$values['hex_g'] = $chars[2].$chars[3];
$values['hex_b'] = $chars[4].$chars[5];
$values['hex_a'] = $chars[6].$chars[7];
// Assembled hex value.
$values['hex'] = $values['hex_r'].$values['hex_g'].$values['hex_b'];
// Return the values.
return $values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.