在c ++中每X字节添加空字节

时间:2013-05-24 13:08:55

标签: c++ winapi byte

嗨,对于我的项目,我需要在char数组中的每个x字节添加空字节,如

unsigned char data[] = {
0x98, 0xB0, 0x26, 0x7E, 0x11, 0x80, 0x9A, 0x79, 
0xE7, 0x46, 0x14, 0xA4, 0x62, 0x7E, 0x06, 0xC0 ...
};

需要:

unsigned char data[] = {
0x98, 0xB0, 0x26, 0x7E, 0x00, 0x11, 0x80, 0x9A, 0x79, 0x00 
0xE7, 0x46, 0x14, 0xA4, 0x00, 0x62, 0x7E, 0x06, 0xC0, 0x00...
};

我需要一个纯粹的winapi函数没有std :: string我尝试了很多东西,但我卡住了 如果可以的话,谢谢你的帮助! :)

1 个答案:

答案 0 :(得分:0)

此函数将在堆上分配的新数组上执行您想要的操作:

unsigned char* Process(const unsigned char* buffer, size_t size, size_t noChars, size_t& newSize)
{
   newSize = size + size/noChars;
   unsigned char* bufferProcessed = new unsigned char[newSize];

   size_t i;
   for (i = 0; i < size/noChars; ++i)
   {
       memcpy(bufferProcessed+(noChars+1)*i, buffer+noChars*i, noChars);
       bufferProcessed[(noChars+1)*(i+1)-1] = '\0';
   }
   if (size%noChars)
       memcpy(bufferProcessed+(noChars+1)*i, buffer+noChars*i, size-noChars*i);

   return bufferProcessed;
}

这个反过来(注意变化!):

unsigned char* ProcessBack(const unsigned char* buffer, size_t size, size_t noChars, size_t& newSize)
{
    newSize = size - size/noChars;
    unsigned char* bufferProcessed = new unsigned char[newSize];

    size_t i;
    for (i = 0; i < size/noChars; ++i)
    {
        memcpy(bufferProcessed+noChars*i, buffer+(1+noChars)*i, noChars);
    }
    if (size%noChars)
        memcpy(bufferProcessed+noChars*i, buffer+(1+noChars)*i, size-noChars*i);

    return bufferProcessed;
}