Jump to content

[SOLVED] Logical Operators on interger values


deveed

Recommended Posts

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.