Page 1 of 1

bitwise / binary questions

Posted: Wed Sep 26, 2007 6:42 pm
by Luke
I am studying a PHP library right now. In the library, they define some simple flags like so...

Code: Select all

define('FLAG_REQUIRED', 0x01); // binary 0001
define('FLAG_OPTIONAL', 0x02); // binary 0010
define('FLAG_ONCE',     0x04); // binary 0100
Then they use these flags to denote whether certain parameters are required, optional, and if they should be only allowed once per component:

Code: Select all

$this->valid_properties = array(
            'SOMETHING'    => FLAG_OPTIONAL | FLAG_ONCE, // binary 0110
            'SOMETHING_ELSE'      => FLAG_OPTIONAL | FLAG_ONCE, // binary 0110
            'SOME_PROPERTY'      => FLAG_REQUIRED | FLAG_ONCE,  // binary 0101
            'PROPALICIOUS'     => FLAG_REQUIRED | FLAG_ONCE, // binary 0101
            'I_AM_PROPERTASTIC' => FLAG_OPTIONAL // binary 0010
        );
Why define these flags as hex? Why not just define them as decimal 1, 2 and 4? I don't understand the benefit here.

EDIT- and also, how would you then enforce this using these? I see later on they do this...

Code: Select all

if(($propdata & FLAG_REQUIRED) && // some other condition) {
                // snip
            }
But I'm kind of lost here.

Posted: Wed Sep 26, 2007 7:36 pm
by Begby
I am not sure why they are defined as hex.... it might be because its a lot easier to tell how many bytes of storage you will need for the flag, if it is like 0x41 you will know that you will need at least 4 bytes to store the value in an unsigned db field.

I am not sure about your second question unless you are asking how the math works.

If you have 1101 and then do a binary AND with 0010 it will return 0000, but if you have 1101 and do a binary AND with 0100 it will return 0100 which evaluates to true.

Posted: Wed Sep 26, 2007 8:00 pm
by volka
Begby wrote:if it is like 0x41 you will know that you will need at least 4 bytes to store the value in an unsigned db field.
one byte would suffice ;)

Re: bitwise / binary questions

Posted: Wed Sep 26, 2007 10:29 pm
by superdezign
The Ninja Space Goat wrote:Why define these flags as hex? Why not just define them as decimal 1, 2 and 4? I don't understand the benefit here.
Makes it easier to use OR, AND, XOR, and NOT, and inform PHP that they are actually hex values. PHP isn't compiled, so I don't think it uses memory the same way as pre-compiled code, and numbers may not be treated the same. I haven't tested this, but maybe you could try replacing the flags with decimal values and see if it works.

Posted: Wed Sep 26, 2007 11:45 pm
by feyd
PHP doesn't really care if you write them in hex versus decimal versus octal.. it's all translated to 32-bit signed binary internally (on most systems.)