记Windows上MingGW中rand()函数一坑

无聊之际想找一发rand函数的实现原理,于是各种include头文件中搜索,发现了一个RAND_MAX的一个宏定义

#define RAND_MAX 0x7ffff

于是写了个函数测试了一下,果然生成的所有随机数都是0 ~ 0x7ffff这个范围。想到随机数产生不了完整的int和long long部分,于是自己手写一个辅助random头文件。

namespace ismdeep{
    
    int randint() {
        int n = sizeof(int)*8;
        int val = 0;
        while (n > 15) {
            val = val | ((int)rand() << (n-15));
            n -= 15;
        }
        val = val | ( (int)rand()>>(15-n) );
        return val;
    }

    long randlong() {
        int n = sizeof(long)*8;
        long val = 0;
        while (n > 15) {
            val = val | ((long)rand() << (n-15));
            n -= 15;
        }
        val = val | ( (long)rand()>>(15-n) );
        return val;
    }

    long long randlonglong() {
        int n = sizeof(long long) * 8;
        long long val = 0;
        while (n > 15) {
            val = val | ((long long)rand() << (n-15));
            n -= 15;
        }
        val = val | ( (long long)rand()>>(15-n) );
        return val;
    }

}
// srand( (unsigned)time( NULL ) );
// cout << ismdeep::randint() << endl;