0

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));
?>

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.