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.
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:
and then defining the
compare(function a bit differently:The trick was the
str_repeatwhich I was not aware of before.