Answer the question
In order to leave comments, you need to log in
How to understand and implement a bitmap?
I somehow saw that it is possible to implement the storage of the states of a particular subject using a bitmap. Those were button states. Each state is encoded by a certain power of two. Once the "start" states have been recorded, they can be operated on using bitwise javascript operators.
Component.State = {
DISABLED: 1,
FOCUSED: 2,
HOVERED: 4,
ACTIVE: 8,
HAS_ICON: 16
}
Component.State[HOVERED | FOCUSED]
Answer the question
In order to leave comments, you need to log in
it will be clearer
states = {
DISABLED: 0b001, // так можно писать двоичные числа
FOCUSED: 0b010,
HOVERED: 0b100,
}
(states.DISABLED | states.HOVERED).toString(2) // .toString(2) - переводит в двоичную
// "101" // поставлены 1 и 3 биты
| is a bitwise OR. & - bitwise AND. each digit is processed separately and, in the case of OR, if at least one number has a unit in this digit, then the result will be 1. Accordingly, 00001 | 00010 = 00011
.
Powers of two are numbers where one is in only one bit. If several such numbers are pro-OR-th, then you get a number where there are units in all the necessary digits. In fact, you assign each state its own rank. Then, where there are units in the number - those states are.
To check that a bit in a number is set, you need to take a bitwise AND and make sure that the result is not 0 (it can be either 0 or some power of two.
These are not bitmaps, but bitwise operations, masking.
Component.State = {
DISABLED: 1,
FOCUSED: 2,
HOVERED: 4,
ACTIVE: 8,
HAS_ICON: 16
} Convert
everything to binary:
DISABLED: 00000001,
FOCUSED: 00000010,
HOVERED: 00000100,
ACTIVE: 00001000,
HAS_ICON: 00
See how the one bit shifts?
Now apply the bitwise OR operation to the selected values:
HOVERED | FOCUSED =
00000100 (4)
+
00000010 (2)
=
00000110 (6)
We mixed two values and got a new one, in which we store the new state.
Now, in order to check that there is some value in the state x=6 = 00000110, we need to check it with a bitwise AND operation and compare with zero:
Is x FOCUSED?
if (x & FOCUSED > 0) => yes, otherwise no: 00000110 & 00000100 = 00000100 > 0 => value IS!
Does x have DISABLED?
if (x & DISABLED > 0) => yes, otherwise no: 00000110 & 00000001 = 00000000 = 0 => no value!
The entry " HOVERED | FOCUSED
" reads "HOVERED or FOCUSED". However, in Russian it should be said "HOVERED and FOCUSED" (analogue: crocodile - long and green").
You can also write this expression " HOVERED + FOCUSED
" - it will be the same, and also more understandable. But this form of recording is bad for those that for two identical signs " HOVERED | HOVERED == HOVERED
", but when added it will not be so.
Let's say the variable x
contains the status of the button. You need to work with this variable like this:
x|=FOCUSED
x&=~FOCUSED
x&FOCUSED?в_фокусе:не_в_фокусе
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question