Ole
Ole

Reputation: 47088

Eliminating dashes from node crypto generated random values?

There's this function in the NPM cuid library:

import * as crypto from "crypto"

var lim = Math.pow(2, 32) - 1;

export function getRandomValue () {
  return Math.abs(crypto.randomBytes(4)
    .readInt32BE(0) / lim)
}

The return value from this should not return values with dashes in it.

However per my test sampling a million values, one value returned contains a dash.

How do we eliminate the dashes?

Someone in an earlier question suggested using % instead of / and this works. I ran 10 million samples and none of them contain dashes, so does this seem like the correct thing to do to the rest of you?

Upvotes: 1

Views: 199

Answers (1)

styfle
styfle

Reputation: 24670

The "dash" is not a hyphen.

It's the scientific notation for a number such as 8.55652615627193e-7.

See 'e' in javascript numbers for a similar question.

You could use num.toString(16) to convert to hexadecimal which looks like 0.00000e5b00000e5b.

Upvotes: 1

Related Questions