生成唯一的序列号序列号

2023-09-12 21:24:12 作者:酷不停

如何生成一个唯一的序列ID存储在无符号长? 1970年以后经过四处秒会是不错的主意,但要求是在一秒钟内的ID有可能会更新,所以第二不会是唯一的!

how to Generate a unique sequence ID to be stored in unsigned long ? Getting seconds elapsed after 1970 would have been good idea but requirement is within a second the id might be updated , so second wont be unique !

推荐答案

如果您的要求是捡东西伪随机,快速,可靠地独特的,而不是用来为crytographic安全目的的要求,我提供了以下

If your requirements are to pick something pseudo random, fast, reliably unique, and not used for requirement for crytographic security purposes, I offer up the following

在Windows 86:

On Windows X86:

__rdtsc() - 约作为良好的序列号,因为它得到。异或高32位的返回值与下32位。作为低32位将循环每两秒钟

__rdtsc() - is about as good of a sequential number as it gets. XOR the upper 32-bits of the return value with the lower 32-bits. As the lower 32-bits will cycle every couple of seconds

#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <intrin.h>
#include <stdint.h>

uint32_t GetPseudoRandomNumber()
{
    uint64_t t = _time64(NULL);
    uint64_t cpu = __rdtsc();
    uint32_t result;
    cpu = cpu ^ t;
    result = (cpu >> 32) ^ (cpu & 0xffffffff);
    return result;
}

uint32_t GetPseudoRandomNumber2()
{
    GUID guid = {};
    uint32_t* pValue = (uint32_t*)&guid;
    uint32_t result;

    CoCreateGuid(&guid);

    result = pValue[0] ^ pValue[1] ^ pValue[2] ^ pValue[3];

    return result;
}

熵的其他来源包括的GetTickCount()(唯一到毫秒)

Other sources of entropy include GetTickCount() (unique to the millisecond)

在Linux上:    刚看完4个字节的/ dev / urandom的

On Linux: Just read 4 bytes from /dev/urandom

 
精彩推荐
图片推荐