如何将const char*复制到c 中的uint8_t []

How to copy const char* to uint8_t [] in c++?

本文关键字:uint8 中的 const char 复制      更新时间:2023-10-16

在以下示例中

const char* msg1 = "hello how are you";

我想复制到 uint8_t msg2[]

如何将MSG1值复制到MSG2?

,因为这是一个'c'ish问题,所以我使用了c风格。

const char* msg1 = "hello how are you";
size_t length = strlen(msg1) + 1;
const char* beg = msg1;
const char* end = msg1 + length;
uint8_t* msg2 = new uint8_t[length];
size_t i = 0;
for (; beg != end; ++beg, ++i)
{
    msg2[i] = (uint8_t)(*beg);
}
std::cout << msg1 << "nn";
std::cout << msg2 << "nn";
delete[] msg2;

输出:

hello how are you
hello how are you

在您的示例中,msg2太小。但是,如果不是(F.E.

 memcpy(msg2, msg1, strlen(msg1)+1);

如果MSG1不是const但可变,请使用类似的东西:

int l = strlen(msg1)+1;
uint8_t *msg2 = new uint8_t[l];
memcpy(msg2, msg1, l);

,但请记住使用delete []

作为编写,您不能将msg1的大小作为编译时间表达式,因此您可能需要编写constexpr char msg1[] = "hello how are you";,因此您可以使用sizeof(msg1)并获得大小数组,而不是指针。然后,您可以将该大小用作msg2的绑定。

如果您不需要修改新数组,则只能在任何实际存在的实现:const uint8_t * const msg2 = reinterpret_cast<const uint8_t*>(msg1);上投放指针。如果需要完全匹配的类型,也可以将其施放为与msg1相同的数组大小的引用。或使msg1数组可修改并使其别名而不是复制。或将msg2初始化为{'h', 'e', ... }。字符常数为 int值,所以这是合法的。

如果要便便复制数组的元素,则可以将其声明为正确的大小和memcpy( msg2, msg1, MSG1_LEN ),也可以编写一个迭代的循环,该循环在msg1上迭代并设置每个msg2[i] = static_cast<uint8_t>(msg1[i])。或push_back msg1的每个元素陷入std::vector<uint8_t>

const char* msg1 = "hello how are you";
uint8_t msg2[] = "hai";

在该示例中,由于msg2太小,因此无法将所有msg1值复制到msg2中。msg1指向18个字符的数组。msg2是长度4的数组。18个字符超过4个。

最简单的解决方案是使用向量。您可以使用以下算法(pseudocode(将数组复制到另一个数组中:

for each element in array at index i
    copy the element at index i into the back of the other array

无需自己实现算法,因为标准库已经为您实施:std::copy。只要源类型隐式转换到目标类型,这种工作正常。如果您需要明确的转换,则可以改用std::transform

我想复制到uint8_t msg2[]

没有uint8_t[]的类型。当然,您可以使用常规数组,例如uint8_t msg2[18],但是您仅限于复制长度为18或以下的数组。可以在运行时设置向量的大小,因此它没有此限制。