views:

366

answers:

3

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;
}
+1  A: 

0xF is hex notation

EDIT:

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

Paul U
+6  A: 

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?

John Millikin
I know it was hexadecimal, I just didn't realise that it was being converted according to the ASCII standard. I thought it was shorthand for 0xFF.
RibaldEddie
ASCII has nothing to do with it. 0xF is 15, 0xFF is 255, 0xFFF is 4095. Like in decimal numbers, undefined digits in hex default to 0.
John Millikin
Right you are. Thanks.
RibaldEddie
+1  A: 

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."

D. Patrick