我正在阅读一些c ++开源代码和c ++的初学者,我发现这段代码很难理解,我不知道这段代码在做什么,为什么要用这种方式编写。有人能给我任何线索吗?(问题部分在rndseq[k] = (rndseq[k] << 8) | (rand() & 0xff)
;)
static unsigned int rndseq[2048];
for (k = 0; k < 2048; k++)
{
rndseq[k] = 0;
for (i=0; i < (int)sizeof(int); ++i)
rndseq[k] = (rndseq[k] << 8) | (rand() & 0xff);
}
(rndseq[k] << 8) | (rand() & 0xff)
这些是二进制运算,(请参阅C中的位运算)
可以翻译成
rndseq[k] * 256 + rand() % 256
代码背后的想法是,创建一个带有随机条目的大数组,但是它的方法太复杂了
我希望这可以帮助您了解逻辑
//we want to fill this array with random numbers
static unsigned int rndseq[2048];
// for each k-entry of the array
for (k = 0; k < 2048; k++)
{
// initialize k-entry with zero
rndseq[k] = 0;
// for each byte in the k-entry integer
for (i=0; i < (int)sizeof(int); ++i)
//on the first iteration rndseq[k] is zero, so
//(rndseq[k] << 8) remains zero.
//(rand() & 0xff) creates a random number in the range [0,255]
//-> in the first iteration rndseq[k] will be set to a random number ([0,255])
//lets say, you have a int32 (4 bytes)
//you need 1 byte to represent 255
//so you have 3 "empty" bytes and 1 filled
//lets say, rand() got the number 1
//than rndseq would have the following value
//0x00-0x00-0x00-0x01
//in the next iteration you shift 1 byte, so
//you get from (rndseq[k] << 8)
//0x00-0x00-0x01-0x00
//the next random-number (still 1 byte) (lets say 2)
//will be stored in now free last byte
//result:
//0x00-0x00-0x01-0x02
//now you repeat, until all bytes are set
//result:
//0x01-0x02-0x03-0x04
rndseq[k] = (rndseq[k] << 8) | (rand() & 0xff);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句