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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This picks a random real number from 0 to 15:
For example, you might get 11.114714370026688.
That’s a bitwise AND of the result with the number 3. The first thing that does is take the number from
dddand convert it to an integer, because the bitwise operators aren’t defined for floating point numbers. So in my example, it treatsdddas the whole number 11.The next thing it does is perform an AND of the two numbers’ binary representations. Eleven in binary is
1011and three is0011. 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 is0011, which is again equal to decimal 3.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
0011in binary and eight is1000, the result is1011– 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), orb(which is eleven).