Chameleon

Chameleon Svn Source Tree

Root/branches/JrCs/i386/libsaio/convert.c

1/*
2 * Convert.c
3 * Implement conversion utility functions
4 * Create UUID parsing functions and gather other conversion routines
5 * --Rek
6 */
7
8#include "convert.h"
9
10/* Return a string that is the representation of a 16 bytes UUID */
11void getStringFromUUID(const uuid_t uuid, uuid_string_t out)
12{
13 sprintf((char*) out, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
14 uuid[0], uuid[1], uuid[2], uuid[3],
15 uuid[4], uuid[5], uuid[6], uuid[7],
16 uuid[8], uuid[9], uuid[10],uuid[11],
17 uuid[12],uuid[13],uuid[14],uuid[15]);
18}
19
20/* Parse an UUID string and return a new allocated UUID */
21uuid_t* newUUIDFromString(const char *source)
22{
23 if (! source) return NULL;
24
25 const char* p = source;
26 int i;
27 int len;
28 char uuid_hex[UUID_LEN*2+1];
29
30 // Check if UUID is valid
31 for (i=0; *p != 0 && i < UUID_LEN*2; p++) {
32 if (*p == '-')
33 continue;
34
35 if (!isxdigit(*p)) {
36 return NULL;
37 }
38 uuid_hex[i++] = *p;
39 }
40
41 // invalid size
42 if (*p != 0 || i != UUID_LEN*2) {
43 return NULL;
44 }
45
46 uuid_hex[i] = 0; // null terminated string
47
48 return convertHexStr2Binary(uuid_hex, &len);
49}
50
51void *convertHexStr2Binary(const char *hexStr, int *outLength)
52{
53 int len;
54 char hexNibble;
55 char hexByte[2];
56 uint8_t binChar;
57 uint8_t *binStr;
58 int hexStrIdx, binStrIdx, hexNibbleIdx;
59
60 len = strlen(hexStr);
61 if (len > 1)
62 {
63 // the resulting binary will be the half size of the input hex string
64 binStr = malloc(len / 2);
65 binStrIdx = 0;
66 hexNibbleIdx = 0;
67 for (hexStrIdx = 0; hexStrIdx < len; hexStrIdx++)
68 {
69 hexNibble = hexStr[hexStrIdx];
70
71 // ignore all chars except valid hex numbers
72 if (hexNibble >= '0' && hexNibble <= '9'
73 || hexNibble >= 'A' && hexNibble <= 'F'
74 || hexNibble >= 'a' && hexNibble <= 'f')
75 {
76 hexByte[hexNibbleIdx++] = hexNibble;
77
78 // found both two nibbles, convert to binary
79 if (hexNibbleIdx == 2)
80 {
81 binChar = 0;
82
83 for (hexNibbleIdx = 0; hexNibbleIdx < sizeof(hexByte); hexNibbleIdx++)
84 {
85 if (hexNibbleIdx > 0) binChar = binChar << 4;
86
87 if (hexByte[hexNibbleIdx] <= '9') binChar += hexByte[hexNibbleIdx] - '0';
88 else if (hexByte[hexNibbleIdx] <= 'F') binChar += hexByte[hexNibbleIdx] - ('A' - 10);
89 else if (hexByte[hexNibbleIdx] <= 'f') binChar += hexByte[hexNibbleIdx] - ('a' - 10);
90 }
91
92 binStr[binStrIdx++] = binChar;
93 hexNibbleIdx = 0;
94 }
95 }
96 }
97 *outLength = binStrIdx;
98 return binStr;
99 }
100 else
101 {
102 *outLength = 0;
103 return NULL;
104 }
105}
106

Archive Download this file

Revision: 126