Understanding JS Computations Using AND, OR, and Hex Bit Numbers

I am trying to understand the part of the code presented here: stack overflow

// returns a valid GUID
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0;
    var v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
});
// "3bce4931-6c75-41ab-afe0-2ec108a30860"

I understand the issue of using the bitwise OR 0 to fill rooms that 3.142 | 0will return an integer, truncating a fraction, but I guess it comes to the use of a hexadecimal number, and lost when we And then or, for example randomNumber & 0x3 | 0x8.

I found that the method has a hexadecimal value toString(the number is not equal!):

0x3.toString() // returns '3'

And I guess that it probably randomNumber & 0x3 | 0x8returns a two-bit value, which is the ascii character (and not just a number) in the right range ... but I guess, and I can’t find a good link that gives me the whole picture.

- / ?

, JS : / hex


:

, , , qaru.site/questions/250/..., ..

, - String.fromCharCode()?

+4
1

, &, | ASCII, v.toString(16). & | .

r 0x0 0xf. : r == abcd, a, b, c d 0 1.

r & 0x3 , ( 3 11). , r & 0x3 == 00cd.

| 0x8 ( 8 1000). , r & 0x3 | 0x8 == 10cd.

r & 0x3 | 0x8 r 10. 0x0 0xf, : 0x8 ( 1000), 0x9 ( 1001), 0xa ( 1010) 0xb ( 1011).

+4

Source: https://habr.com/ru/post/1648868/


All Articles