Reputation: 4666
var ddd = Math.random() * 16;
console.log((ddd & 3 | 8).toString(16));
Help me please. I dont understand how works this operators (| and &) and why this code returns a-f symbols?
Upvotes: 1
Views: 114
Reputation: 95242
This picks a random real number from 0 to 15:
var ddd = Math.random() * 16;
For example, you might get 11.114714370026688.
ddd & 3
That's a bitwise AND of the result with the number 3. The first thing that does is take the number from ddd
and convert it to an integer, because the bitwise operators aren't defined for floating point numbers. So in my example, it treats ddd
as the whole number 11.
The next thing it does is perform an AND of the two numbers' binary representations. Eleven in binary is 1011
and three is 0011
. When you AND them together, you get a binary number that is all zeroes except where there's a 1 in both numbers. Only the last two digits have 1's in both numbers, so the result is 0011
, which is again equal to decimal 3.
| 8
That does a bitwise OR of the result so far (3) with the number 8. OR is similar to AND, but the result has 1's wherever there's a 1 in either number. Since three is still 0011
in binary and eight is 1000
, the result is 1011
- which is back to decimal eleven.
In general, the above calculation sets the 8-bit (third from the right) to 1 and the 4-bit (second from the right) to 0, while leaving the other bits alone. The end result is to take your original random number, which was in the range 0-15, and turn it into one of only four numbers: 8, 9, 10, or 11. So it's a very roundabout way of generating a random number between 8 and 11, inclusive. Math.floor(8 + Math.random()*4)
would have done the same thing in a more straightforward manner.
It then prints the result out in hexadecimal (base 16), so you get 8
, 9
, a
(which is ten in base 16), or b
(which is eleven).
Upvotes: 4
Reputation: 142921
The expression ddd & 2 | 8
is doing bitwise arithmetic by taking the bitwise OR operation of 8 and the bitwise AND operation of ddd
and 2. If you don;t understand bitwise operations, you should consult this article explaining what they are.
The code can return characters in the range a-f because you passed in a radix parameter 16
to the Number.toString
prototype method, which means that it will display the number in hexadecimal.
Upvotes: 5