In lamens terms, what does a bitwise | operator do in Javascript and why is:
8 | 1 ; //9
In lamens terms, what does a bitwise | operator do in Javascript and why is:
8 | 1 ; //9
8 in binary = 1000
1 in binary = 0001
if you take each binary digit and treat them as if statements (1 being true and 0 being false), you get this:
1 || 0 = 1
0 || 0 = 0
0 || 0 = 0
0 || 1 = 1
and the result is 1001, which is 9 in decimal
If it had been 8 & 1, it would go like this:
1 && 0 = 0
0 && 0 = 0
0 && 0 = 0
0 && 1 = 0
and the result would be 0
Here's a quick example of how you might use these:
You would use the OR operator if you wanted to combine masks -
Using an example of file permissions, you may have the following flags:
1st bit - execute (bin - 001, dec - 1)
2nd bit - write (bin - 010, dec - 2)
3rd bit - read (bin - 100, dec - 4)
If you wanted to create a mask for read and execute, you'd do something like read value | execute value
which is 1 | 4
which would give you 5
(101 in bin)
Now you have a mask that you can check a file's permissions to see if it has both of these permissions, using the &
operator:
Example file 1 (has read, write, and execute)
Its permission value is 7 (111 in bin): 111 & 101 = 101, so it does have those perms
Example file 2 (has read and write)
Its permission value is 6 (110 in bin): 110 & 101 = 100, so it only has the 100 (4 in dec) perms (read) of the two provided from the mask
The |
operator is a bitwise OR.
8 (base 10) is 1000 (base 2; binary). 1 is 0001
So, 8 | 1 (base 10) is equal to 1000 | 0001 binary, which is 1001 binary, which is 9 (base 10).
All values on a computer are stored on the hardware in binary format.
1 = 0001
2 = 0010
3 = 0011
4 = 0100
etc.
|
is the OR operater, which combines all bits from both values:
8 - 1000
1 = 0001
--------
9 = 1001
Well, in your example, take the binary representations:
8 = 0b1000
1 = 0b0001
Then apply a logical OR to each bit (hence "bitwise"): For each bit, if either one, the other or both is/are 1 then the result is 1, else the result is 0.
8|1 = 0b1001
Which is 9.
It takes the binary representation of two numbers, and finds the union ("or") between them.
Consider the two you gave:
binary(8) = 1000
binary(1) = 0001
So, if a bit is 1 in the first number (8) or the second number (1) or if it is 1 in both then it is carried down to the result.
So, 8 | 1 = 9
, because 1001
in binary is the result of the "or" operation and is 9 in decimal