Devang Rathod
Devang Rathod

Reputation: 6736

Convert decimal to hex using PHP

How to convert decimal value to hex using php?

Dec : 68-55-230-06-04-89

I want hex value like this

Hex : 44-37-E0-06-04-59 but instead of this its display 44-37-E0-6-4-59

echo $test = dechex(68)."-".dechex(55)."-".dechex(230)."-".dechex(06)."-".dechex(04)."-".dechex(89);

It's give me output : 44-37-E0-6-4-59 // without 06-04

I want output something like 44-37-E0-06-04-59

Upvotes: 0

Views: 3999

Answers (4)

Ravindra Shekhawat
Ravindra Shekhawat

Reputation: 4353

$dec= "68-55-230-06-04-89";

$arr= split("-",$dec);

foreach($arr as $key => $num)

{

    $arr[$key]=sprintf('%02X',dechex ($num));

}


//required results Array ( [0] => 44 [1] => 37 [2] => e6 [3] => 6 [04] => 4 [05] => 59 )

print_r($arr);

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

For getting 44-37-E0-06-04-59 just add 0 as below,

sprintf('%02X-%02X-%02X-%02X-%02X-%02X', 68, 55, 230, 06, 04, 89);

Upvotes: 1

h3n
h3n

Reputation: 898

something like that should work if you assume that there are maximum of FF between the dashes:

$foo = explode("-", $dec);
foreach ($foo as $dec_value) {
    echo ($dec_value > 16) ? dechex($dec_value) : "0".dechex($dec_value);
}

Upvotes: 0

sectus
sectus

Reputation: 15464

You can try sprintf

sprintf('%02X-%02X-%02X-%02X-%02X-%02X', 68, 55, 230, 6, 4, 89);

Upvotes: 2

Related Questions