我有4个字节的空间来创建一个随机数。最后一个字节用于容器和插槽(与此问题无关)所以我有3个字节来填充当前时间(epoch也会这样做)
到目前为止,我有以下内容:
uint32_t create_handle(uint8_t container_id, uint8_t file_slot)
{
uint32_t handle;
time_t now = time(NULL);
handle = ((now << 24) & ~(0xFF));
handle += (container_id << 4) + file_slot; /* Last byte is 4 bits of container + 4 bits of slot */
return handle;
}
这是对的吗?我能够生成随机数,但我无法评估它是否有效。有没有更好的方法呢?
答案 0 :(得分:1)
你现在正在转移24,只留下8.我想你只想换班8. & ~(0xff)
是多余的。
如何使用其中一个随机数库?或者你永远不会需要每秒多于一个手柄?
答案 1 :(得分:1)
srand (time(NULL))
提供随机化种子。 rand ()
获取随机数。