问题
I am currently trying to convert an integer variable to the value of a static uint8_t array in the Arduino IDE.
I am using:
#include <U8x8lib.h>
And I do understand that uint8_t acts similarly to the byte type.
Currently, the array has a set value:
static uint8_t hello[] = "world";
From my perspective, "world" looks like a string, so I thought I would start with creating a string variable:
String world = "world";
static uint8_t hello[] = world;
This did not work and gave me the error:
initializer fails to determine size of 'hello'
If I do the same, but instead change "world" to an int like below...
int world = 1;
static uint8_t hello[] = world;
I get the same error being:
initializer fails to determine size of 'hello'
I have been successful in converting the uint8_t array to a string through the following process:
static uint8_t hello[] = "world";
String helloconverted = String((const char*)hello);
I don't understand the following:
How a uint8_t array can have a string-like input and work fine, but not when a variable is involved
How to create a string variable as the input for the uint8_t array
How to create a int variable as the input for the uint8_t array
Thanks in advance for your assistance.
回答1:
How a uint8_t array can have a string-like input and work fine, but not when a variable is involved
String literal is essentially an array of chars with terminating null. So
static uint8_t hello[] = "world";
Is essentially
static uint8_t hello[] = {'w','o','r','l','d','\0'};
Which is also a normal array copy initialization, and the size needed is auto-deduced from the value, this is why you can use [] and not [size]
How to create a int variable as the input for the uint8_t array
Since size of int
is known at compile time you could create an array of size of int
and copy int
value to it byte by byte with memcpy
:
int world = 1;
static uint8_t hello[sizeof(world)];
memcpy(hello, &world, sizeof(hello));
How to create a string variable as the input for the uint8_t array
You need to know the length of the String
beforehand so you can create an array big enough to fit the String
value:
String world = "Hello"; // 5 chars
static uint8_t hello[5];
world.toCharArray((char *)hello, sizeof(hello));
Depending on what you need, you might want to also handle terminating null.
来源:https://stackoverflow.com/questions/52289439/input-process-and-type-for-static-uint8-t-array