Question

In some PHP I need to compare two strings, but only on the bits that are set as one in the bitmask. How would I implement such a behavior?

I've tried:

$string1='aaabbb';
$string2='ababbb';
$bitmask='101101';
function compare($string1, $string2, $bitmask){
    $resultBitmask=(~($string1 ^ $string2)|~$bitmask);
} 

For clarity's sake, I've written ff bytes as 1 in the bitmask for illustrative purposes. They would actually be ff in hex when a bitmask is generated. Same goes for 0 being null bytes.

The string and the bitmask are always different lengths each time the function is called. I've managed to get a set of bits for comparison, but am unable to check whether they are all set since the lenths differ. At this time, I've been using preg_match with a regex that matches any number of ff bytes, but is there a more elegant solution?

Edit: Since the strings are any length up to 4096 bits long, they cannot be converted to numbers.

Was it helpful?

Solution 2

Self-solved:

Since this will repeat with many strings of the same length during a run, but have different lengths between runs, I need to check that the resulting string after the bitwise operations is all ones and the correct length. I realized that this string full of ones can be generated when needed, which is quite rarely, once every 1000 or so string comparisons. I can generate the string before runs as follows:

$ones=str_repeat(chr(255), $byte_length);

and then defining the compare( function a bit differently:

function compare($string1, $string2, $bitmask){
    global $ones;
    $resultBitmask=(~($string1 ^ $string2)|~$bitmask);
    if ($resultBitmask=$ones){
         return 1;
    } else {return 0};
} 

The trick was the str_repeat which I was not aware of before.

OTHER TIPS

It's not the flashest way of doing it but:

$stillTheSame = true;
for($i=0;$i<=strlen($bitmask); $i++)
{
  if($bitmask[$i] == 1)
  {
    if($string1[$i] != $string2[$i]) 
    {
      $stillTheSame = false;
      break;
    }  
  }
}

Not sure fof your actual checking logic, but this should help hopefully.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top