问题是,为什么在单独的方法调用中获取相同数量的字节的行为会根据在单个方法调用中调用 5000 个字节还是使用长度为 1 的字节数组进行 5000 个方法调用返回不同的字节。
看下面的例子:在终端中打印 21,而不是 5000,(5000 除以 256 得到 ~19,这使得 21 个匹配很可能是简单的巧合)。
Random rand = new Random(0);
byte tmp1[] = new byte[5000];
rand.nextBytes(tmp1);
rand = new Random(0);
byte tmp2[] = new byte[5000];
byte tmp3[] = new byte[1];
for(int i = 0; i < 5000;i++)
{
rand.nextBytes(tmp3);
tmp2[i] =tmp3[0];
}
int matches = 0;
for(int i = 0; i < 5000;i++)
{
if(tmp1[i] == tmp2[i])
{
matches++;
}
}
System.out.println(matches);
更重要的是,无论我是使用长度为 5000 的数组调用该方法一次还是使用长度为 2500 的数组调用该方法两次,等等,任何破解它以生成相同字节的方法都无关。
编辑:下面的帖子完美地回答了问题,一次接收字节 4 完全解决了问题。 测试代码如下,返回4000:
Random rand1 = new Random(0);
byte tmp11[] = new byte[4000];
rand1.nextBytes(tmp11);
rand1 = new Random(0);
byte tmp22[] = new byte[4000];
byte tmp33[] = new byte[4];
for(int i = 0; i < 1000;i++)
{
rand1.nextBytes(tmp33);
for(int a = 0; a < 4;a++)
{
tmp22[(i*4)+a] = tmp33[a];
}
}
int matches1 = 0;
for(int i = 0; i < 4000;i++)
{
if(tmp11[i] == tmp22[i])
{
matches1++;
}
}
System.out.println(matches1);
最佳答案
这是因为 java 使用 nextInt() 来填充字节并将另外 3 个 int 值字节添加到数组中。基本上,从随机生成器接收到的每个 int 都会填充数组的 4 个字节。我将添加一个示例。
首先是 javadoc:
The method nextBytes is implemented by class Random as if by:
public void nextBytes(byte[] bytes) { for (int i = 0; i < bytes.length; ) for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4); n-- > 0; rnd >>= 8) bytes[i++] = (byte)rnd; }
现在展示我们可以做的示例:
Random rand = new Random(0);
rand.nextBytes(tmp1);
System.out.println(tmp1[0]);
System.out.println(tmp1[4]);
rand = new Random(0);
rand.nextBytes(tmp3);
System.out.println(tmp3[0]);
rand.nextBytes(tmp3);
System.out.println(tmp3[0]);
打印: 96 56 96 56,因为 int 的大小是 4。基本上它获取 1 个 int (即 4 个字节)并将其添加到字节数组的位置 0、1、2、3 中。当您使用 byte[1] 调用它时,它会获取相同的 int 并将相同的字节添加到值 0,但 int 中的其他 3 个字节会丢失。这就是为什么你会出现不一致的情况。您得到的数字 21 只是巧合。
关于java - java 中的 Random.nextBytes(bytes[]) 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51132512/