Tak
Tak

Reputation: 11704

Bitwise comparison in PHP

I confess I don't really know what I'm doing! I'm pulling some data from SecondLife and parsing it in PHP. The data is an integer from llGetRegionFlags which, in my case, returns 1048592

Now I need to do a bitwise comparison in PHP to figure out which flags are true/false. For example 0x00000040 is used for the "block terraform" flag.

The notations are in hex for each flag, and I have an integer to test against, and the PHP manual suggests integers and shows examples in binary.

So my question really is, given an integer and some hex flags, how do I go about doing the bitwise comparison in PHP? Brainfried! Thanks in advance

Upvotes: 1

Views: 2747

Answers (4)

Nechoha
Nechoha

Reputation: 3

Usually the bitflags are checked with a piece of code like this:

$blockTerraformFlag = 0x00000040;
$isBlockTerraform = (($RegionFlags & $blockTerraformFlag) == $blockTerraformFlag);

Upvotes: 0

Nick Andriopoulos
Nick Andriopoulos

Reputation: 10643

You could define the bits required, and check against them to make it look clean. ie

define('BLOCK_TERAFORM', 0x00000040);

....

if($data & BLOCK_TERAFORM) {
  ... do something ...
}

Upvotes: 0

James Tracy
James Tracy

Reputation: 40

To determine if a particular bit is turned on, use the & (AND) operator:

if ($data & 0x00000040) {
    // block terraform flag is true
}

If the bit is turned on, the AND operator will return a positive number. If it is turned off, then the AND operator will result in a zero.

Upvotes: 1

mcryan
mcryan

Reputation: 1576

Use a single AND & / OR |

if ($value1 & $value2) { }

The PHP Manual explains more: http://php.net/manual/en/language.operators.bitwise.php

Upvotes: 0

Related Questions