我有一个像这样的 iBeacon UUID
"3bdb098f-b8b0-4d1b-baa2-0d93eb7169c4"
,我需要它看起来非常像这样:
static uint8_t adv_data[31] = { 0x02,0x01,0x06, 0x1A,0xFF,0x4C,0x00,0x02,0x15,0x71,0x3d,0x00,0x00,0x50,0x3e,0x4c,0x75,0xba,0x94,0x31,0x48,0xf1,0x8d,0x94,0x1e,0x00,0x00,0x00,0x00,0xC5 };
我需要一种方法来在代码中转换它,但是“手动”转换这个的一次性方法也很酷(而且arduino代码不必每次都处理转换)
一次读取两个字符,将其转换为十六进制值对应的数字。循环进行。遇到
'-'
字符时跳过它。将数组中的“当前”元素设置为该值。将“当前”设置为数组中的下一个元素。
类似这样的伪代码
while (not at end of string)
{
char1 = get next character from string;
char2 = get next character from string;
value = make int from hex characters(char1, char2);
array[current++] = value;
}
这应该可以解决你的问题
char *uuid = "3bdb098f-b8b0-4d1b-baa2-0d93eb7169c4";
static uint8_t adv_data[32]; //your uuid has 32 byte of data
// This algo will work for any size of uuid regardless where the hypen is placed
// However, you have to make sure that the destination have enough space.
int strCounter=0; // need two counters: one for uuid string (size=38) and
int hexCounter=0; // another one for destination adv_data (size=32)
while (i<strlen(uuid))
{
if (uuid[strCounter] == '-')
{
strCounter++; //go to the next element
continue;
}
// convert the character to string
char str[2] = "\0";
str[0] = uuid[strCounter];
// convert string to int base 16
adv_data[hexCounter]= (uint8_t)atoi(str,16);
strCounter++;
hexCounter++;
}
使用库函数转换为数字形式的另一种方法是,您可以简单地对字符
'0'
减去 0 - 9
,对字符 'a' - 10
减去 'W'
(或简单地 a - f
)来执行转换。例如:
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define MAXC 32
int main (int argc, char **argv) {
char *uuid = argc > 1 ? argv[1] : "3bdb098f-b8b0-4d1b-baa2-0d93eb7169c4";
uint8_t data[MAXC] = {0};
size_t i, ui = 0, di = 0, ulen = strlen (uuid);
for (;di < MAXC && ui < ulen; ui++, di++) {
if (uuid[ui] == '-') ui++; /* advance past any '-' */
/* convert to lower-case */
if ('A' <= uuid[ui] && uuid[ui] <= 'Z') uuid[ui] |= (1 << 5);
data[di] = ('0' <= uuid[ui] && uuid[ui] <= '9') ? uuid[ui] - '0' :
uuid[ui] - 'W'; /* convert to uint8_t */
}
if (di == MAXC && ui != ulen) { /* validate all chars fit in data */
fprintf (stderr, "error: uuid string exceeds storage.\n");
return 1;
}
printf ("\n original: %s\n unsigned: ", uuid);
for (i = 0; i < di; i++)
putchar (data[i] + (data[i] < 10 ? '0' : 'W'));
putchar ('\n');
return 0;
}
示例输出
$ ./bin/uuid_to_uint8_t
original: 3bdb098f-b8b0-4d1b-baa2-0d93eb7169c4
unsigned: 3bdb098fb8b04d1bbaa20d93eb7169c4
(注意: 在尝试转换以进行额外验证之前,您可以添加进一步检查以确保
uuid[ui]
是有效的 十六进制 字符或 '-'
)。