[英]How to understand the following code in C?
我正在使用PCG随机数生成软件包,无法理解以下代码。
time(NULL) ^ (intptr_t)&printf
这是函数生成随机种子的参数:
void pcg32_srandom(uint64_t seed, uint64_t seq)
在主要功能中,其用法如下:
pcg32_srandom(time(NULL) ^ (intptr_t)&printf, 54u);
顺便说一句,我也想问为什么“ 54u”应该这样写?
让我们分解一下...
/* original: pcg32_srandom(time(NULL) ^ (intptr_t)&printf, 54u); */
uint64_t a = time(NULL);
uint64_t b = (intptr_t)&printf;
uint64_t c = a ^ b;
uint64_t d = 54u;
printf("a=%llx\n", (unsigned long long) a); /* no guessing about length */
printf("b=%llx\n", (unsigned long long) b); /* (thank you @chux) */
printf("c=%llx\n", (unsigned long long) c);
printf("d=%llx\n", (unsigned long long) d);
pcg32_srandom( a ^ b, d);
所以... ^是按位xor运算符(编辑:我最初写的是或 )。 添加printf应该可以帮助您跟踪代码在做什么。 显然,代码会不时地将某些内容与printf函数的地址进行异或(这很聪明,我之前从未见过)。
54u上的u可能是原始作者谨慎的。 在进行位操作时,通常不需要带符号的数字。 这有一些背景: http : //soundsoftware.ac.uk/c-pitfall-unsigned
我们可以在此处查看pcg32_srandom()的API: http ://www.pcg-random.org/using-pcg-c-basic.html
and these variants for the global RNG:
void pcg32_srandom(uint64_t initstate, uint64_t initseq)
uint32_t pcg32_random()
uint32_t pcg32_boundedrand(uint32_t bound)
因此,似乎他们正在尝试为随机数生成器“ initstate”提供种子,并且由于某种原因,希望使用54u作为“ initseq”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.