使用UUID获取唯一ID

Publish: December 3, 2015 Category: 默认分类 No Comments

一、先安装libuuid开发库:

yum -y install libuuid-devel


二、有两种方法编码:

1. 第一种方法: (通用方法: 生成的结果为: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

#include <uuid/uuid.h>

void get_uuid(char *uuid)
{
    uuid_t _uuid;
    uuid_generate(_uuid);
    uuid_unparse(_uuid, uuid);
}


2. 第二种方法: (不带横线的32个大写字符:)

#include <uuid/uuid.h>

// return: 不等于16失败
int get_uuid(char *uuid, size_t uuid_size)
{
    uuid_t _uuid;
    uuid_generate(_uuid);
    unsigned char *p = _uuid;
    int i;
    char ch[5] = {0}; 
    for (i=0; i<sizeof(uuid_t); i++,p++) {
        snprintf(ch, sizeof(ch), "%02X", *p); 
        uuid[i*2] = ch[0];
        uuid[i*2+1] = ch[1];
        //printf("%02x", *p);   
    }    
    return i;
}


三、编译与使用:

char uuid[1024] = {0};
get_uuid(uuid, sizeof(uuid));
printf("%s\n", uuid);
gcc -g -o test test.c -luuid



Tags: uuid

Related Posts:
  • [尚无相关文章]

Leave a Comment