V
V
vaniapooh2011-11-18 10:27:33
Web development
vaniapooh, 2011-11-18 10:27:33

Applying bitwise operators in PHP and Javascript?

Everyone knows about bitwise operators ( & , | , ^ , >> , << , etc.) in the most popular web programming languages ​​(PHP and Javascript definitely have them!). In books, too, they always write about them, because they exist, and without them the book will be incomplete. And now the question is: what examples of the use of these operators in web programming tasks do you know?
PS On this topic, I found only this in Q&A: habrahabr.ru/qa/813/

Answer the question

In order to leave comments, you need to log in

5 answer(s)
K
korvindest, 2011-11-18
@korvindest

Well, for example, if you need to implement an algorithm for finding a solution by dividing a segment in half, then it is more efficient to use shift to the right, rather than dividing by 2.
In addition, bitwise operators are relevant when working with RGB color if all three (or 4) components are stored in one int.
You can also remember about converting to binary and hexadecimal calculus for a convenient representation of the session id or something like that.
Well, these are just examples...
Naturally, all this is needed, only in cases where there are no ready-made functions built into the language.

S
Sergey Beresnev, 2011-11-18
@sectus

Bit operations are used to use flags. Take at least mistakes . It is necessary to expose all errors, except for depricated, then we write:
E_ALL & ~E_DEPRECATED.

I
Ivan Shalganov, 2011-11-18
@Aco

I have an object in the project that has 42 different states, like reset, completed with an error, in the process of this, in the process of this ... etc. 1 bit is allocated for each state, so all possible states fit into one property of the object. So, there are many places where I need to decide what to do based on these flags, for example, compare 2 pieces of code.

if($this->_sock && !empty($this->_opts["keep-alive"]) && $this->_is_opened && $this->_step == "proceed") {
}

or
if($this->_state & self::CAN_PROCEED) {
}

in this way, instead of a bunch of properties and checking keys for arrays / objects, you can do one bit operation

M
mark_ablov, 2011-11-18
@mark_ablov

For example, you can not have 32 boolean fields in mysql, but “pack” everything into one int.

A
Andrey Shiryaev, 2011-11-19
@Claud

And as an example with a web smell, this is getting Google PR parameters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question