Reputation: 1391
Not sure what I am doing wrong here. When I pad zeros in front of a hexadecimal number it seems to change the number.
$number=1741;
strtoupper(dechex($number))
output is 6CD
sprintf('%03x', strtoupper(dechex($number))
output is 006
Upvotes: 4
Views: 4696
Reputation: 400
The accepted answer says to use sprintf
twice. I don't see the value in doing this twice, %x
accepts the same padding parameters as %d
does and so this can be done in one function call.
$number = 141;
$hex = sprintf('%03X', $number); // 08D
So to answer the question, just remove the strtoupper(dechex(...))
and the sprintf
you have will work.
echo sprintf('%03x', $number); // 06d
echo sprintf('%03X', $number); // 06D
Upvotes: 7
Reputation: 9583
For padding zero of a number just use sprintf
, If you need a hexadecimal number then you need to use something like sprintf
with a valid format for showing hexadecimal number.
Example:
Syntax: sprintf(format,arg1,arg2,arg++)
Format:
So, use a sprintf
to get the hexadeimal
number and then use another sprintf
to get the zero padding number.
$number = 141;
$hex = sprintf("%X", $number); //8D
$s = sprintf('%03d', $hex); // 08D
Upvotes: 3