What is the practical use of bitwise operators in PHP?

Asked

Viewed 1,072 times

13

Operators bit by bit, used to manipulate specific bits, are somewhat unusual (not to say rare) their use in an application PHP. 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?

  • 2

    The same as in any other language. Know if a number is even, multiply/divide by 2 potentials faster, join flags, make bit maps to filter DB results, etc. Knowing how to use, there is a lot that is more practical and fast bit by bit. It is that usually who learns only PHP is very superficial, since the language is basically used for simple scripts (which are artificially complicated with academicism of other languages, in many cases).

  • 2

    @Bacco answers there with a few examples :D

  • 1

    @rray hope someone does it, I just put a comment to advance the subject. It would be nice an answer with small algorithms example. If I have some time later, I can try to do something. But I prefer the community to post examples, it’s cooler with several answers. If you (or someone) want to take some of the examples I said and use it in your own response, feel free.

4 answers

11


For those who stayed floating, let’s go to a practical example in the real world

Imagine you built a system where you need to implement several 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 an SQL query would look something like SELECT editar, adicionar, deletar FROM ...

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

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

Using bitwise operators, it could simplify so

tabela permissões:
     usuario_id
     bit_flag

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

With only 1 numerical column, you can identify several permissions.

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

With that, 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 precisely the sum of 1, 2, 4, 8 and 64.

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

In the system you define how 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.

  • 2

    Great! He may be simple but he started to clear his head.

1

PHP is a general purpose language, 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 file with binary format
  • network communication, and the protocol is binary
  • compact representation of various 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, hash calculation or check digits. With bitwise operators, one can implement these things in pure PHP, otherwise it would be necessary to write in C.

1

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 contact with the hardware ...

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

The best answer I can give besides evoking academic situations is to indicate some practice, this to get away from the basic answer of administration permissions that are wrong at 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 need to have a unique number on the service. This will have your registration on one of the data servers that will be several of support for the service. To shuffle further, the identifier must also contain a style of check Digit for instant validation.

One way to achieve this is with bit by bit.

Instead of having three camps, we can have a single camp that brings all of us together. 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-bit.

Thus and taking into account the limit of 32 bits (fictional 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

So we can join these three distinct fields into an integer only, thus obtaining an always unique number and extra functionality. I intend to make it clear that PHP this type of operations are very necessary.

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

This type of field/structure is named after bit field. From the 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.

Many are the advantages in using Bit Fields and in real cases are widely used.

  • Yes, the comment was just a generalization and a small example of bit-by-bit usage.

0

I found it indispensable to use bitwise in this algorithm. It is very fast to find combinations of values over a value. In case I’m researching 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;
            }
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.