如何从字符串中每隔16个字节复制一次数据

How to copy every 16 bytes of data from a string?

本文关键字:复制 数据 一次 字节 16个 字符串      更新时间:2023-10-16

我必须将数据复制到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