如何将const char*复制到c 中的uint8_t []
How to copy const char* to uint8_t [] in c++?
在以下示例中
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或以下的数组。可以在运行时设置向量的大小,因此它没有此限制。
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 如何将元素从 Swift 中的 [UnsafeMutablePointer<UInt8>] 转换为 C++ 中的 UInt8 *
- 我如何将uint8_t (SDL中的Uint8)转换为字符串