9

How do I echo the binary value of an integer in PHP? I tried using pack('S',$var) but its showing no results...

1
  • Do you mean the binary representation, or the binary string of "0" and "1"? Commented May 16, 2012 at 10:14

2 Answers 2

13
decbin($number);

Returns a string containing a binary representation of the given number argument.

For instance decbin(26) will return 11010

Source docs for decbin()

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

3 Comments

I guess he is more intersted by the string representing the number that it's actual binary representation (try echo decbin(9223372036854775808) on 64 bit system, or echo decbin(2147483648) on a 32 bit one. and for that base_convert is better suited
mathroc, I have no idea what you're talking about (ignorance basically) but the few times I've needed to convert those two types, I've used decbin without any issues. Since you seem to know what you're talking about, please provide an answer and I'll gladly upvote it :)
the answer from Chief17 is what I mean. it's just that decbin is limit to the size of C-integer, if you try the example in my previous answer, you'll find that it print "0". decbin works well but you have to be carefull of the size of your number (i guess little/big endian system could make a differece there too)
8
<?php
echo base_convert($number, 10, 2);
?>

http://php.net/manual/en/function.base-convert.php

string base_convert ( string $number , int $frombase , int $tobase )

2 Comments

+1 for generic solution and showing a little known function. Also, another option would be printf("%b", $number)
And if you want to store what @CarlosCampderrós says in a variable instead of displaying it, you could do $var = sprint("%b",$number);

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.