我有 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;
}
这是正确的吗?我能够生成随机数,但我无法评估它是否有效。有更好的方法吗?
最佳答案
你现在移动 24,只剩下 8。我想你只想移动 8。& ~(0xff)
是多余的。
使用其中一个随机数库怎么样?还是您永远不需要每秒处理一个以上的句柄?
关于c - 如何使用当前时间创建随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20258325/