How do I echo the binary value of an integer in PHP? I tried using pack('S',$var) but its showing no results...
2 Answers
decbin($number);
Returns a string containing a binary representation of the given number argument.
For instance decbin(26) will return 11010
3 Comments
Mathieu
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
Juan Cortés
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 :)Mathieu
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)
<?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
Carlos Campderrós
+1 for generic solution and showing a little known function. Also, another option would be
printf("%b", $number)Juan Cortés
And if you want to store what @CarlosCampderrós says in a variable instead of displaying it, you could do
$var = sprint("%b",$number);