deveed Posted January 23, 2009 Share Posted January 23, 2009 There is a really nifty trick I have been using in VB where I use the logical operator AND on integers. In VB each of the integers is converted into a binary string, the logical operator is then applied against the separate columns of the string and the out put string is converted back into an integer. For instance 1 AND 2: becomes 01 AND 10, = (0 AND 1) . (1 AND 0) = (0) . (0) = 0 Where as (more complex example) 26 AND 14 = 11010 AND 01110 = (1 AND 0).(1 AND 1).(0 AND 1).(1 AND 1).(0 AND 0) = (0).(1).(0).(1).(0) = 01010 = 10 I was hoping to use this function in PHP, but the AND Operator (&&) works differently. From looking at the results I'm getting I think it is assuming all positive integers to = TRUE and then running the AND operator. e.g.: 26 && 14 = TRUE && TRUE = TRUE. Does anyone know of a way I can get PHP to do Binary-Based AND operations on Integers? It can be a really useful function. Link to comment https://forums.phpfreaks.com/topic/142097-solved-logical-operators-on-interger-values/ Share on other sites More sharing options...
deveed Posted January 23, 2009 Author Share Posted January 23, 2009 Ended up writing my own version of the function: function inetgerAnd($a, $b){ $a = (int)$a; $b = (int)$b; $bina = base_convert($a, 10, 2); $binb = base_convert($b, 10, 2); $bina=str_pad($bina, strlen($binb), "0", STR_PAD_LEFT); $binb=str_pad($binb, strlen($bina), "0", STR_PAD_LEFT); $binAnd=''; for($i=0;$i<strlen($bina);$i++){ $binAnd.=substr($bina,$i,1)+substr($binb,$i,1)==2?'1':'0'; } return base_convert($binAnd,2,10); } But if anyone knows a better way, let me know. Link to comment https://forums.phpfreaks.com/topic/142097-solved-logical-operators-on-interger-values/#findComment-744195 Share on other sites More sharing options...
Daniel0 Posted January 23, 2009 Share Posted January 23, 2009 I guess this is because VB's logical and bitwise operators share the same syntax. That's not the case in PHP. In PHP, && is a "logical and" whereas & is "binary and". See: http://php.net/operators.bitwise Link to comment https://forums.phpfreaks.com/topic/142097-solved-logical-operators-on-interger-values/#findComment-744206 Share on other sites More sharing options...
deveed Posted January 23, 2009 Author Share Posted January 23, 2009 Ha! "Bitwise Operator" - always wondered what it was call. Thanks Dan. Link to comment https://forums.phpfreaks.com/topic/142097-solved-logical-operators-on-interger-values/#findComment-744354 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.