What is the practical use of bitwise operators in PHP?

12

The bitwise bit operators used to manipulate specific bits are somewhat unusual (not to say rare) 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 because of the higher level of contact with the hardware (Microcontroller, Arduino, Raspberry).

In PHP, what is the practical use of them?

    
asked by anonymous 01.03.2016 / 21:56

4 answers

11

For those who have floated, let's take 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 of a text group, etc.

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

tabela permissões:
     usuario_id
     editar
     adicionar
     deletar
     desativar
     ver

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

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

You will need to create new columns and add implementations to system scripts.

Using bitwise operators, you could simplify this way

tabela permissões:
     usuario_id
     bit_flag

So you ask, how will I know if this user can edit, add, etc?

With only 1 numeric column, you can identify various 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 want 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.

    
02.03.2016 / 20:52
1

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

  • interpret a binary format file
  • Make network communication, and the protocol is binary
  • compact representation of several 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 verifier digits. With bitwise operators, you can implement these things in pure PHP, otherwise you would need to write in C.
02.03.2016 / 20:00
1

Here's an interesting question, but I totally disagree with the statement of your question where it mentions:

  

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

Of course, this is only one of several applications of bit a bit , however, in PHP and although it is a language of script developed in C, it does not leave and depending on the need of each implementation to be required bitwise operability.

The best response I can give beyond evoking academic situations is to point out some practice, to get away 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 a case of applicability:

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

One way to achieve this is with bitwise.

Instead of having three fields, we can have a single field that adds 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 true for 64 bits.

So, considering the 32-bit limit (a dummy schematic just to portray what I'm exposing) 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

So we were able to merge these three distinct fields into one integer only, resulting in an always unique number and extra functionality. I think it's a good thing to say that, as a% of this type of operation is very much needed.

In this case, and by way of example, imagine that the user delivers his unique code to the service. You can immediately validate the integrity of the delivered identifier, then immediately point to the server where your registration is located and get your data. This is somehow how some systems work.

This field / structure type is named PHP . From the wiki you 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 to using Bit fields and in real cases they are widely used.

    
02.03.2016 / 18:55
0

I found it essential to use bitwise in this algorithm. It is very fast to find combinations of values about a value. In case I am 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;
            }
        }
    
05.10.2016 / 14:39