如何从字符串中每隔16个字节复制一次数据
How to copy every 16 bytes of data from a string?
我必须将数据复制到16字节的集合中。我该如何用一种简单的方法做到这一点?我已经想出了下面的算法,但我如何知道是否添加了null终止符?谢谢!:)
std::string input
//get message to send to client
std::cout << "Enter message to send (type /q to quit) : ";
getline(std::cin, input);
input += 'n';
const char *data = input.c_str();
len = strlen(data)+1;
int max_len =17;
//split msg into 16 bytes
for(int i = 0; i < len ; i+=max_len)
{
char tempStr[max_len];
//get next 16 bytes of msg and store
for(int j = 0; j < max_len ; j++)
{
tempStr[j] = data[j+i];
}//end of for loop
//Do some stuff to tempStr
}
在代码中,不会添加字符串终止符。您还可以在副本之间跳过一个字符(因为您将max_len
作为17
,而只复制16
个字符)。
我会提出一个使用标准库的解决方案:
std::string::const_iterator pos = input.begin();
while (pos < input.end())
{
// Create a temporary string containing 17 "null" characters
char tmp[17] = {' ' };
// Make sure we co no copy beyond the end
std::string::const_iterator end =
(pos + 16 < input.end() ? pos + 16 : input.end());
// Do the actual copying
std::copy(pos, end, tmp);
// Advance position
pos += 16;
// Use the string in 'tmp', it is properly terminated
}
const char* data = input.c_str();
int len = input.size(); // don't add 1
for (int i=0; i<len; i+=16)
{
char tempStr[17];
tempStr[16] = 0;
strncpy(tempStr, data + i, 16);
// Do some stuff to tempStr
}
根据您对tempStr的实际操作,可能会有一个根本不需要复制的解决方案。
for (int i=0; i<len; i+=16)
{
llvm::StringRef sref(data + i, data + std::min(i+16,len));
// use sref
}
llvm::StringRef
相关文章:
- 在 C++ AMP 数组中复制数据多少次?
- 字符串是否在其构造函数中复制数据
- 在不复制数据的情况下,将double数组转换为只有double成员的structs数组
- 有没有一种方法可以在不复制数据的情况下从string_view创建字符串流
- 如何在不复制数据的情况下将 cv::Mat 转换为 2d 标准::矢量
- C++ 在节点内存储对数据对象的引用,而不复制数据
- 是否可以在不分配内存或复制数据的情况下构造对象?
- 如何在不复制数据的情况下在平面数组和多维数组之间进行转换?
- C 2D char阵列有时会在随机位置复制数据
- 在不复制数据的情况下更改 opencv mat 中的列顺序
- 有没有办法将 EGL 绘制到 /dev/fb1 而不是 /dev/fb0,而无需在树莓派上复制数据
- 使用C 和目标C从原始图像中复制数据
- 给定 myvector.start() 和 myvector.end(),我想在不复制数据的情况下创建 myvector
- 复制数据时出现奇怪错误
- 如何在 C/C++ 中从数组末尾开始复制数据
- glTexImage2D 复制数据或仅指定数据
- 如何在C++中从void指针复制数据
- 在不复制数据的情况下将OpenCV Mat发送到MATLAB工作区的方法
- 如何使用 GPU-DMA 从 GPU-CUDA 代码来复制数据
- 在矢量到矢量中复制数据<float> <Mat> (Opencv/C++)