typedef struct
{
unsigned char *buffer;//待切割数据
unsigned int bufferLen;//待切割数据长度
unsigned int index;//当前切割数据索引
unsigned int dataMaxLen;//每次切割数据最大长度
unsigned int resultDataLen;//当前索引切割数据长度
unsigned int resultIndex;//切割数据在buffer中的索引
}GetBuff_TypeDef;
int getBufferByIndex(GetBuff_TypeDef *buffInfo)
{
if(buffInfo->buffer == 0 || buffInfo->bufferLen == 0 || buffInfo->dataMaxLen == 0)
{
return -1;//参数错误
}
//计算需要切割的次数
unsigned int cutCount = buffInfo->bufferLen / buffInfo->dataMaxLen;
if(buffInfo->bufferLen % buffInfo->dataMaxLen != 0)
{
cutCount++;
}
if(buffInfo->index > cutCount)
{
return -2;//索引超出范围
}
//计算当前索引切割数据长度
if(buffInfo->index == cutCount - 1)
{
if(buffInfo->bufferLen % buffInfo->dataMaxLen != 0)
{
buffInfo->resultDataLen = buffInfo->bufferLen % buffInfo->dataMaxLen;
}
else
{
buffInfo->resultDataLen = buffInfo->dataMaxLen;
}
buffInfo->resultIndex = buffInfo->index * buffInfo->dataMaxLen;
return 1;
}
else
{
buffInfo->resultDataLen = buffInfo->dataMaxLen;
}
//计算当前索引切割数据在buffer中的索引
buffInfo->resultIndex = buffInfo->index * buffInfo->dataMaxLen;
return 0;
}
void testBuff()
{
GetBuff_TypeDef buffInfo;
buffInfo.buffer = malloc(1000+5);
buffInfo.bufferLen = 1000+5;
buffInfo.dataMaxLen = 100;
buffInfo.index = 0;
for(int i = 0; i < 1000+5; i++)
{
buffInfo.buffer[i] = i;
}
int ret = 0;
while (ret == 0)
{
ret = getBufferByIndex(&buffInfo);
if(ret >= 0)
{
logDebug("------------------------------");
logDebug("index:%d, resultDataLen:%d, resultIndex:%d", buffInfo.index, buffInfo.resultDataLen, buffInfo.resultIndex);
for(int i = 0; i < buffInfo.resultDataLen; i++)
{
logDebug("buffer[%d]:%d", buffInfo.resultIndex + i, buffInfo.buffer[buffInfo.resultIndex + i]);
}
buffInfo.index++;
}
}
}