RibaldEddie
RibaldEddie

Reputation: 5136

How does this JavaScript function create a GUID?

I came across this JavaScript function and I don't understand quite what it's doing, especially with the use of 0xF.

What does the 0xF do, exactly. It looks like a null nibble to me.

function()
{
    var g = "";
    for(var i = 0; i < 32; i++)
        g += Math.floor(Math.random() * 0xF).toString(0xF)
    return g;
}

Upvotes: 2

Views: 1800

Answers (3)

D. Patrick
D. Patrick

Reputation: 3022

All it's doing is creating random number s and converting them to hex.

I just did a little investigating . . . it is taking a random number, multiplying it by 15 (0xF == 15) and then converting it to hex . . . the toString argument takes a radix. That's the same as saying 0xF.toString(10). That'll convert 0xF to decimal and return "15."

Upvotes: 1

John Millikin
John Millikin

Reputation: 200916

0xF == 15. It's simply hexadecimal notation.

However, that snippet is not actually creating a GUID, it's just stringing a bunch of random integers together. It's not possible to create a GUID in JavaScript, because generating one requires parameters that the VM can't access (network address, etc).


See also my answer to this question: How to create a GUID in Javascript?

Upvotes: 5

Paul U
Paul U

Reputation: 681

0xF is hex notation

EDIT:

It looks like it's picking a random character 0-9 A-F 32 times

Upvotes: 1

Related Questions