Eliminating dashes from node crypto generated random values?

故事扮演 提交于 2020-03-25 12:32:49

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/60676476/eliminating-dashes-from-node-crypto-generated-random-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!