无法理解这段C ++代码

用户名

我正在阅读一些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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

无法理解Makefile中的这段代码

来自分类Dev

无法理解混淆的C代码

来自分类Dev

无法理解混淆的C代码

来自分类Dev

无法理解这行代码的C ++

来自分类Dev

无法理解这段JS代码【数组和过滤器】

来自分类Dev

我无法理解这段代码(对于 React/Redux)是如何工作的

来自分类Dev

无法理解代码片段

来自分类Dev

无法理解部分代码

来自分类Dev

无法理解python代码

来自分类Dev

我无法理解这段代码中到底发生了什么。子集功能的最后争论是做什么的?

来自分类Dev

无法理解代码/函数调用

来自分类Dev

无法理解连接建立代码

来自分类Dev

无法理解以下熊猫代码

来自分类Dev

伪代码无法理解行

来自分类Dev

无法理解此代码的输出?

来自分类Dev

无法理解JAVA代码行

来自分类Dev

无法理解代码/函数调用

来自分类Dev

无法理解部分代码(位操作)

来自分类Dev

我无法理解以下代码

来自分类Dev

无法理解 ruby 代码片段

来自分类Dev

无法理解工作代码与损坏代码之间的区别

来自分类Dev

无法理解工作代码与破损代码之间的区别

来自分类Dev

非常简单的代码,并出现错误C2712,无法理解原因

来自分类Dev

无法理解C#代码的这一部分

来自分类Dev

我无法理解以下代码中的位置 c=0 和 l=0

来自分类Dev

返回一个枚举,无法理解代码行

来自分类Dev

无法理解Java 1.7 PopupFactory源代码

来自分类Dev

无法理解字符串置换Java代码

来自分类Dev

Phalcon DI phpStorm IDE无法理解我的代码