How do you create a random 64 bit number? [closed]

丶灬走出姿态 提交于 2019-12-20 07:48:46

问题


I have part of a spec that requires me to create a random 64 bit number with the following converted to a character string : (0 to 2^63 - 1)

I have no idea what this means in the brackets, can anyone help?


回答1:


The parenthesis is set-builder notation for a random 64 bit number between 0 and 2^63-1, not including 0 nor 2^63-1.




回答2:


Since you didn't specify a programming language I'll give a solution in C and then you can adapt it to whatever programming language you might be using if it turns out not to be C (or a close relative).

You can just call arc4random twice and concatenate the values:

 #include <stdint.h>
 #include <stdlib.h>

 int64_t rand64(void)
 {
     uint64_t r_lo = (uint64_t)arc4random();
     uint64_t r_hi = (uint64_t)arc4random();
     return (int64_t)((r_hi << 31) | (r_low >> 1));
 }

You can convert this to a hex ASCII string quite easily:

 char s[17];

 int64_t r = rand64();
 sprintf(s, "%16llx", r);

(If you need it as decimal or some other format then just modify the sprintf format string accordingly).



来源:https://stackoverflow.com/questions/17656312/how-do-you-create-a-random-64-bit-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!