What is the practical use of bitwise operators in PHP?

The bitwise operators, used for handling specific bits, are somewhat unusual (not to say Rare) their use in a PHP application. If we talk about escovação de bits in compiled languages, such as C/C++, it is easier to understand due to the higher level of contact with the hardware (microcontroller, Arduino, Raspberry).

In PHP, what is the practical use of using them?

 13
Author: Maniero, 2016-03-01

4 answers

For those who have been floating, let's go to a practical example in the real world

Imagine that you have built a system where you need to implement multiple levels of access.

Example, allow or deny a system Area, allow or deny editing a text group, etc.

Normally we would do something exhausting and difficult to manage like this

tabela permissões:
     usuario_id
     editar
     adicionar
     deletar
     desativar
     ver

In a SQL query would look something like SELECT editar, adicionar, deletar FROM ...

Sounds simple though, imagine when you need to add more permissions.

Will have to create new columns and add implementations in the system scripts.

Using bitwise operators, you could simplify

tabela permissões:
     usuario_id
     bit_flag

Then you ask, How am I going to know if this user can edit, add, etc?

With only 1 numeric column, you can identify multiple permissions.

Example, suppose the query SELECT bit_flag FROM ... returns the number 79.

With this we have the following routine:

$rs = 79; // o que retornou do banco

function showPermission($rs, $b)
{
    return 'Acesso '.$b.' '.(($rs & $b)? 'permitido' : 'negado');
}

echo showPermission($rs, 1).PHP_EOL.'<br />';
echo showPermission($rs, 2).PHP_EOL.'<br />';
echo showPermission($rs, 4).PHP_EOL.'<br />';
echo showPermission($rs, 8).PHP_EOL.'<br />';
echo showPermission($rs, 16).PHP_EOL.'<br />';
echo showPermission($rs, 32).PHP_EOL.'<br />';
echo showPermission($rs, 64).PHP_EOL.'<br />';
echo showPermission($rs, 128).PHP_EOL.'<br />';

Will Return:

Acesso 1 permitido
Acesso 2 permitido
Acesso 4 permitido
Acesso 8 permitido
Acesso 16 negado
Acesso 32 negado
Acesso 64 permitido
Acesso 128 negado

Note that 79 is just the sum of 1, 2, 4, 8, and 64.

Modify the number to 78 and you will see that permission 1 will change to"denied".

In the system you define as you like what each operand represents.

Example,

1 -> representa adicionar
2 -> representa editar
4 -> representa deletar

This is just a simple example of what you can do with bitwise operators. Not only in PHP but in other languages as well.

 11
Author: Daniel Omine, 2016-03-02 19:52:19

PHP is a general purpose language, it can be used for potentially anything. Situations arise when even a high-level language needs to interact with binary numbers and bitwise operations. For example:

  • interpret a file with binary format
  • Do network communication, and the protocol is binary
  • compact representation of multiple states ,flags, or yes/no options. A number from 0 to 255 can represent 8 Independent States ,and " read" each bit is faster using bitwise operators
  • encryption, calculation of hashes or checking digits. With bitwise operators, one can implement these things in pure PHP, otherwise it would be necessary to write in C.
 1
Author: epx, 2016-03-02 19:00:30

Here is an interesting question, but I totally disagree with the statement of your question Where You mention:

... in compiled languages,such as C/C++, it is easier to understand due to the higher level of hardware contact ...

It is certain that this is only one of several applications of bit a bit, however, in PHP and despite being a language of script developed in C, it does not leave and depending on the need of each implementation to be necessary all the operability bitwise.

The best answer I can give besides evoking academic situations is to indicate some practice, this to escape a little from the basic answer of administration permissions that are wrong on many levels and have nothing to do with the real world of a programmer.

So here's an applicability case:

Imagine a unique identifier for an online service where any user will have to have a unique number on the service. This will have your registration on one of the data servers that will be several service support. To shuffle further, the handle must still contain a style of check digit for instant validation.

one way to achieve this is bitwise.

Instead of having three fields, we can have a single field that aggregates all of them. Even the three fields would not meet the requirement to have a unique identifier.

Imagine a 32-bit integer, but the same is valid for 64 bits.

Thus and taking into account the limit of 32 bits (fictitious scheme only to portray what I expose) we can group the bits as follows:

00000000 - 0000000000000000000 - 0000 = valor único num inteiro de 32 bits
    |               |              |
    |               |              |-- 4 bits - até 15 valor do check-digit
    |               |
    |               |-- 20 bits - até 1.048.575 valor único na tabela do srv
    |              
    |--- 8 bits - índice do servidor até 255 servidores

Thus we can combine these three distinct fields into a single integer, thus obtaining a number always unique and of extra functionality. I think expose well, that also in PHP this type of operations are very necessary.

In this case I put and as an example imagine that the user delivers their unique code to the service. Immediately it is possible to validate the integrity of the identifier delivered, then immediately point to the server where your registration is located and obtain your data. This is in a way, how some systems work.

This field / structure type is named bit field. From wiki get:

A bit field is a term used in computer programming to store multiple, logical, neighboring bits, where each of the sets of bits, and single bits can be addressed. A bit field is most commonly used to represent integral types of known, fixed bit-width.

There are many advantages in the use of bit fields and in real cases they are widely used.

 1
Author: chambelix, 2016-03-02 22:05:12

I found it indispensable to use bitwise in this algorithm. It is very quick to find combinations of values over a value. In case I'm searching 17.2 the algorithm will return me the key b and c + d...

        $values     = array('a' => '12.8', 'b' => '17.2', 'c' => '10.2', 'd' => '5');
        $target     = explode('.', number_format(17.2, 2)); // VALOR ESPERADO
        $len        = count($values);


        for($i = 1; $i < pow(2, $len); $i++){
            $soma   = 0;
            $set    = array();
            for($j = 0; $j < $len; $j++){
                if(1 << $j & $i){ // MAGICA
                    $set[] = $j;
                    $soma += $values[$j];
                }
            }

            $soma   = explode('.', number_format($soma, 2));
            if($soma[0] == $target[0] && $soma[1] == $target[1]){
                foreach($set as $pos){
                    $ids[] = $values[$pos];
                }
                return $ids;
            }
        }
 0
Author: Rafael L Ramon, 2016-10-05 12:46:28