我有一个像"3bdb098f-b8b0-4d1b-baa2-0d93eb7169c4"
这样的iBeacon UUID,我需要它看起来非常像:
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代码不会每次都处理转换)
答案 0 :(得分:3)
一次红色两个字符,将它们转换为与十六进制值对应的数字。做一个循环。遇到'-'
字符时跳过该字符。将数组中的“current”元素设置为值。将“current”设置为数组中的下一个元素。
像这样的伪代码
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;
}
答案 1 :(得分:1)
这应该适用于您的问题
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++;
}
答案 2 :(得分:1)
使用库函数转换为数字形式的替代方法,您只需为字符'0'
和0 - 9
(或简称'a' - 10
)减去'W'
字符{ {1}}预先进行转化。例如:
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]
)。