uint8_t 数组如何具有类似字符串的输入并正常工作,但是
当涉及变量时不
字符串文字本质上是一个以 null 结尾的字符数组。所以
static uint8_t hello[] = "world";
本质上是
static uint8_t hello[] = {'w','o','r','l','d','\0'};
这也是一个普通的数组复制初始化,所需的大小是从值自动推导出来的,这就是为什么你可以使用 [] 而不是 [size]
如何创建 int 变量作为 uint8_t 数组的输入
由于尺寸为int
在编译时已知您可以创建一个大小为int
并复制int
逐字节地赋值给它memcpy
:
int world = 1;
static uint8_t hello[sizeof(world)];
memcpy(hello, &world, sizeof(hello));
如何创建字符串变量作为 uint8_t 数组的输入
你需要知道长度String
事先这样你就可以创建一个足够大的数组来容纳String
value:
String world = "Hello"; // 5 chars
static uint8_t hello[5];
world.toCharArray((char *)hello, sizeof(hello));
根据您的需要,您可能还想处理终止 null。