crypto.getRandomValues(new Uint32Array(1))[0] / lim可以为负吗? [英] Can crypto.getRandomValues(new Uint32Array(1))[0] / lim ever be negative?

查看:359
本文介绍了crypto.getRandomValues(new Uint32Array(1))[0] / lim可以为负吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好奇表达式 crypto.getRandomValues(new Uint32Array(1))[0] / lim 是否可以为负。

Curious whether the expression crypto.getRandomValues(new Uint32Array(1))[0] / lim can ever be negative.

我正在转换的代码在其周围放置了 Math.abs 包装器,但是我们中有些人认为将它设为负数是不可能的,所以只想

The code I'm converting puts a Math.abs wrapper around it, but some of us think that it's impossible for it to be negative, so just wanted to see what the rest of you think?

var lim = Math.pow(2, 32) - 1;
crypto.getRandomValues(new Uint32Array(1))[0] / lim);

这是有关更多上下文的相关问题:
将getRandomValue.browser从cuid转换为Typescript?

This is the related question for more context: Converting getRandomValue.browser from cuid to Typescript?

该库具有一个 getRandomValue() nodejs函数,如下所示:

The library has a getRandomValue() nodejs function that looks like this:

import * as crypto from "crypto"

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

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

我认为对于浏览器来说, Math.abs 调用被保留,即使它似乎没有必要,也很可能是错误的。

I think for the browser, the Math.abs call was kept even though it seems it is not necessary, and quite possibly incorrect.

推荐答案

在这种情况下,使用 Math.abs()会是错误的!

In this case, the use of Math.abs() would be wrong!

有问题的值,因此上面的声明是 UInt32 ...无符号的32位整数。

The value in question, so says the declaration above, is UInt32 ... unsigned 32-bit integer.

这只是意味着最左位(最高有效位)不是解释为符号位。但是,这不会防止您在假定 MSB = 1 表示负数的情况下无意中使用该值。

This simply means that the leftmost bit (most significant bit) is not to be interpreted as a sign-bit. This does not, however, prevent you from inadvertently using the value in some context which would assume that MSB=1 means "negative."

不过,使用 abs()可能是错误,因为这会转换如果发现 MSB = 1 ,则将整个位模式转换为完全不同的位模式。由于MSB只是组成该值的32位中的一个,因此在假定它是符号位的情况下对它进行任何操作都是错误的。而且,您还需要注意不要将它显示为负数,因为它不会显示为负数。该数量为32位长,而不是31+符号。确保它总是这样。

Nonetheless, it would be wrong for you to use abs() because this would convert the entire bit-pattern, if it finds that MSB=1, into an entirely different bit-pattern. Since the MSB is simply "one of the 32 bits which comprises the value," it is dead-wrong to do anything to it which assumes that it's a sign-bit. And you also want to take care that it never gets displayed as a negative number, because it isn't. This quantity is 32 bits long, not 31+sign. Be sure it always looks that way.

这篇关于crypto.getRandomValues(new Uint32Array(1))[0] / lim可以为负吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆