
Question:
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:
<ol><li>How a uint8_t array can have a string-like input and work fine, but not when a variable is involved
</li> <li>How to create a string variable as the input for the uint8_t array
</li> <li>How to create a int variable as the input for the uint8_t array
</li> </ol>Thanks in advance for your assistance.
Answer1:<blockquote>
How a uint8_t array can have a string-like input and work fine, but not when a variable is involved
</blockquote>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]
<blockquote>How to create a int variable as the input for the uint8_t array
</blockquote>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));
<blockquote>
How to create a string variable as the input for the uint8_t array
</blockquote>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.