0

How do I convert a binary number (i.e. 1111111) to hexadecimal (i.e. 7f) using PHP? I recognize I could do dechex(bindec('1111111'));, however, I am certain that this is not the right way.

I tried bin2hex('1111111') but it resulted in 31313131313131.

0

4 Answers 4

8

Your solution is fine. You can also use base_convert.

$binary = '1111111';
echo base_convert($binary, 2, 16); // 7f

But keep in mind that php is not built for calculations. It is built for working with strings.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Sergey. This seems a little better (or at least more readable).
1
dechex(bindec($binary));

It is the right way, you are putting extra ")"(Closing Parenthesis) in the end...

Reference: http://php.net/manual/en/function.bin2hex.php

1 Comment

Why reference bin2hex()? From the name, one would think it would work, however, not the case.
0

You can also try this function:

<?php

function hexentities($str) {
$return = '';
for($i = 0; $i < strlen($str); $i++) {
    $return .= '&#x'.bin2hex(substr($str, $i, 1)).';';
}
return $return;
 }

?>

Comments

0

try this:

<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>

look at this link for more info http://php.net/manual/en/function.bin2hex.php

2 Comments

While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run.
You can edit your answer by pressing "edit" on the bottom left. Go ahead, try it out :)

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.