I'm trying to understand a piece of code shared here: https://stackoverflow.com/a/2117523/2586761
// 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 from the question Using bitwise OR 0 to floor a number that a 3.142 | 0
will return an integer by truncating the fraction, but I'm guessing when it comes to applying this to hex numbers, and lost when we AND then OR like: randomNumber & 0x3 | 0x8
.
I've discovered that a hex value has a toString
method (a number doesn't!):
0x3.toString() // returns '3'
And I'm guessing that maybe randomNumber & 0x3 | 0x8
is returning a two bit value which is an ascii character (not just a number) in the desired range... but I'm guessing, and I can't find a nice reference which gives me the whole picture.
Can anyone step me through it / suggest a reference?
This question seems related, but doesn't deal with JS specifically, or match my example: bitwise and logical AND/OR in terms of hex result
Update:
I've since notice that there are a bunch of great answers on the original question which explore the question, in particular https://stackoverflow.com/a/28921801/2586761, but none of them answer all my questions..
In particular, how does a number get converted to a character without using something like String.fromCharCode()
?