在代码中找不到错误

时间:2012-09-21 10:49:04

标签: c

我写加密\解密系统(原型)。 该系统有188字节的数据包。争抢:

加密(Python)的:

#key = 40
packet[4]+packet[40:]+packet[4:40]

解密(C):

//in_buffer - main char* massive
//offs - offset of packet (length 188)
//key - int for separator (40 in example before)

void encryption(byte* in_buffer, int offs, int key)
{
  byte temp[188];
  int i;
  //write packet[4:40] to temp
  for(i = 4;i < key; i++)
  {  
    temp[i] = in_buffer[offs+i];
  }
  //write packet[40:] to top
  for(i = 4;i < 188 - key+4; i++)
  {  
    in_buffer[offs+i] = in_buffer[offs+i+key-4];
  }
  //write packet[4:40] of temp to in_buffer[152:]
  for(i = 4;i < key; i++)
  {  
    in_buffer[offs+i+188-key] = temp[i];
  }
}

适用于key = 96,但不适用于任何其他键!为什么呢?

1 个答案:

答案 0 :(得分:0)

所有数组下标算法都很讨厌且容易出错。使用memcpy将各个部分“追加”到位:

byte temp[188];
int pos = 0;

memcpy(temp + pos, in_buffer, 4); // append in_buffer[:4]
pos += 4;
memcpy(temp + pos, in_buffer + 188 - key + 4, key - 4); // append in_buffer[188-key+4:188]
pos += key-4;
memcpy(temp + pos, in_buffer + 4, 188 - key); // append in_buffer[4:188-key+4]