在Python中我这样做:
import random
while True:
x = random.randint(0xF,0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140)
print hex(x)[2:66].lower()
如何使用 C 或 C++ 做到这一点?
最佳答案
使用GNU MP library ,这可以这样完成:
#include <stdio.h>
#include <ctype.h>
#include <gmp.h>
void randint(mpz_t rop, gmp_randstate_t state, mpz_t from, mpz_t to) {
mpz_t range;
mpz_init(range);
/* range = to - from + 1 */
mpz_sub(range, to, from);
mpz_add_ui(range, range, 1);
/* rop = random number in [0, range) */
mpz_urandomm(rop, state, range);
/* rop += from */
mpz_add(rop, rop, from);
mpz_clear(range);
}
int main(void) {
char str[1024]; /* allocate enough memory */
gmp_randstate_t state;
mpz_t low, high;
mpz_t ret;
gmp_randinit_default(state);
mpz_init(ret);
mpz_init_set_str(low, "F", 16);
mpz_init_set_str(high, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140", 16);
for(;;) {
randint(ret, state, low, high);
str[0]='0'; str[1]='x';
mpz_get_str(str + 2, 16, ret);
if (str[0] != '\0' && str[1] != '\0') {
int i;
for (i = 2; i < 66 && str[i] != '\0'; i++) putchar(tolower(str[i]));
}
putchar('\n');
}
/* the control won't come here */
#if 0
mpz_clear(low);
mpz_clear(high);
mpz_clear(ret);
gmp_randclear(state);
return 0;
#endif
}
关于c++ - 如何在c或c++中循环生成随机256位十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33325814/