[英]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.