简体   繁体   English

crypto.getRandomValues(new Uint32Array(1))[0] / lim 可以为负数吗?

[英]Can crypto.getRandomValues(new Uint32Array(1))[0] / lim ever be negative?

Curious whether the expression crypto.getRandomValues(new Uint32Array(1))[0] / lim can ever be negative.好奇表达式crypto.getRandomValues(new Uint32Array(1))[0] / lim是否可以为负数。

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?我正在转换的代码在它周围放置了一个Math.abs包装器,但我们中的一些人认为它不可能是负数,所以只是想看看你们其他人的想法?

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

This is the related question for more context: Converting getRandomValue.browser from cuid to Typescript?这是更多上下文的相关问题: Converting getRandomValue.browser from cuid to Typescript?

The library has a getRandomValue() nodejs function that looks like this:该库有一个getRandomValue() nodejs 函数,如下所示:

import * as crypto from "crypto"

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

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

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!在这种情况下,使用Math.abs()将是错误的!

The value in question, so says the declaration above, is UInt32 ... unsigned 32-bit integer.有问题的值,正如上面的声明所说,是UInt32 ... 无符号 32 位整数。

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."这不,但是,防止意外使用在某些情况下,它的值假设, MSB=1表示“负面”。

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.尽管如此,您使用abs()错误的,因为如果发现MSB=1 ,这会将整个位模式转换为完全不同的位模式。 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.由于 MSB 只是“包含值的 32 位之一”,因此假设它是符号位的任何操作都是错误的。 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.这个数量是 32 位长,而不是 31+符号。 Be sure it always looks that way.确保它看起来总是那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM