Mencarta Posted January 11, 2010 Share Posted January 11, 2010 How would I convert an integer to its binary form? I want to take a character and translate it to binary. Here is my code so far: $char = A$char = (int) $char Thanks. Link to comment Share on other sites More sharing options...
Mencarta Posted January 11, 2010 Author Share Posted January 11, 2010 Nevermind, I found the answer. Link to comment Share on other sites More sharing options...
justsomeguy Posted January 11, 2010 Share Posted January 11, 2010 I'm not sure if casting as int will work, the ord function is specifically for returning the ASCII value of a character, so returning the ASCII value of A would give 65.http://www.php.net/manual/en/function.ord.phpOnce you have the decimal ASCII value, you can use the pack function to format it as a binary string. A format of "c" would be appropriate to use for this.http://www.php.net/manual/en/function.pack.phpOther examples on that page as well. Link to comment Share on other sites More sharing options...
Mencarta Posted January 12, 2010 Author Share Posted January 12, 2010 I just used decbin() as explained here: http://php.net/manual/en/function.decbin.php Link to comment Share on other sites More sharing options...
boen_robot Posted January 12, 2010 Share Posted January 12, 2010 Note that if you want to check if the number has a certain bit set (or not), it will probably be faster to use a bitwise operator, like "|" or "&", like so: $int = 5;//101 in binary$mark = 2;//10 in binary$check = $int & $mark;//2; 10 in binaryif ($check === $mark) {//true If you just want to display it, decbin() it is. Link to comment Share on other sites More sharing options...
justsomeguy Posted January 12, 2010 Share Posted January 12, 2010 In that example $check would be 0, if it's using and on 5 and 2. If it was 6 and 2 then check would be 2. Link to comment Share on other sites More sharing options...
boen_robot Posted January 12, 2010 Share Posted January 12, 2010 In that example $check would be 0, if it's using and on 5 and 2. If it was 6 and 2 then check would be 2.Opps... indeed... I partly copied and reworked another example I had, and I forgot to update the comments accordingly. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.