生成唯一的序列号 [英] Generate unique sequence ID

查看:191
本文介绍了生成唯一的序列号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何生成一个唯一的序列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个字节<一个href="http://myonlineusb.word$p$pss.com/2011/06/10/what-is-the-difference-between-devrandom-and-devurandom/"相对=nofollow>的/ dev / urandom的

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

这篇关于生成唯一的序列号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆