如何在C中生成GUID? [英] How to generate a GUID in C?

查看:527
本文介绍了如何在C中生成GUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成要插入到SQLite数据库中的向导(即,数据库本身不提供支持).但是,我想控制某些属性:

I want to generate guids to insert into a SQLite database (i.e. no support from the db itself). However, I would like to have control over certain properties:

  1. 用于产生增加的guid值的有序性.
  2. 计算机独立性.数据库是公共数据库,可能会(也可能不希望)向导允许某人将数据追溯到特定计算机.
  3. 足够"的随机性. guid是数据库中的键,该键将与许多其他db合并,并且可能变得很大,这意味着像许多算法一样伪造guid不好.
  4. 我可以使用系统特定的API进行处理,但请同时链接Windows和Linux函数,并且首选SQLite之类的东西,在这里我可以使用别人编写的代码.
  5. 我也希望可以在商业应用程序中使用的代码.

推荐答案

您可以使用或查看Boost.Uuid的代码:

You can either use or look at the code of Boost.Uuid :

http://www.boost.org/doc /libs/1_47_0/libs/uuid/index.html

这是一个C ++库,但是您仍然可以在内部找到代码编写者如何在多个系统上检索Uuid.上次检查(2010年1月)时,我至少发现了以下针对Windows和Linux/Solaris的实现(此信息可能已过时):

It is a C++ library, but still, you can find inside how the code author retrieved the Uuid on multiple systems. Last time I checked (january 2010), I found at least the following implementations for Windows and Linux/Solaris (this info could be outdated):

打开文件到/dev/urandom,并读取足够的字节(16)以组成GUID/UUID.

Open a file to /dev/urandom and read enough bytes (16) to make up a GUID/UUID.

使用以下WinAPI函数

Use the following WinAPI functions

  • CryptAcquireContext to acquire a random context
  • CryptReleaseContext to release the acquired random context
  • CryptGenRandom to generate enough bytes to make up a GUID/UUID

GUID/UUID上的Wikipedia页面上有您可以使用/研究的替代实现的列表:

The Wikipedia page on GUID/UUID has a list of alternative implementations you could use/study:

https://en.wikipedia.org/wiki/UUID#Implementations

有一个GUID/UUID类型始终是随机的(

There is a GUID/UUID type which is always random (the version 4), meaning that to be compatible with other GUID/UUID semantics, you should respect that.

现在,您希望及时订购GUID/UUID.做到这一点而又不削弱GUID/UUID随机性的唯一方法是在16字节的GUID/UUID前面加上一个无符号整数(这会使您的标识符数据成为20字节或更多,具体取决于整数).只需生成一个GUID/UUID,然后增加整数即可.

Now, you want the GUID/UUID to be ordered in time. The only way to do that without weakening the GUID/UUID randomness would be to prefix the 16-byte GUID/UUID with an unsigned integer (which would make your identifier data 20-bytes, or more, depending on your integer). Just generate a GUID/UUID, and increase the integer.

这篇关于如何在C中生成GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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