Jane N.
Jane N.

Reputation: 37

Problem when converting between bases and formating the output

The objective is to convert a dec base number between 0 and 255 into a hex base number. The hex base number has to be written in a form XX. So eg 60_10=3c_16, but also 5_10=05_16.

For example:

Number 60 in dec base is 3c in hex base.

The following code works:

<?php
echo dechex(60);
?>

The output is: 3c

Bingo.

And now: Why is the output of the following code 03 instead of 3c? What can I do to make it 3c?

<?php
$br=60;
echo sprintf("%02x", dechex($br));
?>

Upvotes: 0

Views: 34

Answers (2)

Robert
Robert

Reputation: 21

Proper usage

See https://www.php.net/sprintf

It works when you pass the dec value to the function.

<?php
echo sprintf('%02x', 60);

Output

3c

Upvotes: 2

Nigel Ren
Nigel Ren

Reputation: 57131

When you use

sprintf("%02x", dechex($br));

with 3c (the result of dechex()), the x in the format indicates

x The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).

so it expects an integer and will convert this to 3.

x does the conversion for you and no need for the dechex.....

echo sprintf("%02x", $br);

Upvotes: 1

Related Questions