I use binary code to handle my overwrites in my database, but now I need to lookup about the rules are match or not match to this i have follow rules.
When I use php I try to use it like MySQL match:
$overwirtes = 5;
if ( decbin($overwirtes) & decbin(1) )
{
// unlock title
}
if ( decbin($overwirtes) & decbin(2) )
{
// unlock desc
}
if ( decbin($overwirtes) & decbin(4) )
{
// unlock price
}
if ( decbin($overwirtes) & decbin(8) )
{
// unlock stock
}
What I expect it's title and price are unlock and desc and stock are lock, but something go wrong and php will not accept binary like MySQL, can somebody tell me what I do wrong here, I'm still new to work on Binary code as rules.
You run into a "funny" problem. And this is that decbin()
returns a string.
Now if both operands of the bitwise AND operator are strings the operation is preformed with the ASCII values of the strings.
Also a quote from the manual which shows this too:
If both operands for the &, | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer.
So what does that mean in your specific example?
Let's take the second if statement:
$overwirtes = 5;
decbin($overwirtes) & decbin(2)
Well technical this should be evaluated as followed:
0000 0101 (5)
0000 0010 (2)
---------- &
0000 0000 = 0 (FALSE)
But since both operands are string the bitwise AND takes the ASCII values of both strings which here would be this:
0011 0101 (53)
0011 0010 (50)
---------- &
0011 0000 = "48" (TRUE)
So that's why all conditions in your code evaluates as TRUE.
But now how to solve this? Simple, just change 1 operand of the operation to an integer. So you can just remove the decbin()
call from 1, 2, 4, 8.
You can also then see in the manual(quote above) when 1 operand isn't a string (here an integer) that both operands gets implicit casted to an integer. And you also receive an integer.
So your code should look something like this:
$overwirtes = 5;
if ( decbin($overwirtes) & 1)
{
// unlock title
}
if ( decbin($overwirtes) & 2)
{
// unlock desc
}
if ( decbin($overwirtes) & 4)
{
// unlock price
}
if ( decbin($overwirtes) & 8)
{
// unlock stock
}