我无法根据我想要的大小截断缓冲区。我有点困惑为什么我得到错误的结果?即使我对 memcpy() 的使用是正确的。我也阅读了手册页。我在这里做错了什么?
我想要实现的目标:
Buff: 00 83 00 00 16 0a 44 00 00 00 00 bd 0e 8a 0c 61 01 13 51 24 ad 9a 0b 1c 0e ff ff 00
复制从bd开始的字节,也就是第12个字节到结尾-
期望的输出应该是:
bd 0e 8a 0c 61 01 13 51 24 ad 9a 0b 1c 0e ff ff 00
这是我的代码: 我正在接收来自串行设备的响应,我需要截断一些字节。
void rx_dev(transport, int addr, const void *buf, unsigned count) {
uint8_t s[1024];
uint8_t *p;
memset (s, 0, sizeof(s));
// This below function does only the hex parsing.
hex_parse(s, sizeof(s), buf, count);
printf("* %02x %s\n", addr, s);
printf("Count: %zu\n", count);
p = s;
printf("p* %s\n", p);
// I'm doing this check to avoid something greater than 14.
if (count > 14) {
memcpy(p, s+11, count-11);
printf("*Trim:%s\n", p);
}
}
编辑:添加了更多细节
int hex_parse(char *out, unsigned size, const void *buf, unsigned count)
{
const uint8_t *p = buf;
unsigned i;
int n = 0;
if (count)
{
if (n + 2 < size)
{
out[n+0] = hexchars[(p[0] >> 4) & 15];
out[n+1] = hexchars[p[0] & 15];
}
n += 2;
}
for (i = 1; i < count; i++) {
if (n + 3 < size)
{
out[n+0] = ' ';
out[n+1] = hexchars[(p[i] >> 4) & 15];
out[n+2] = hexchars[p[i] & 15];
}
n += 3;
}
if (n < size)
out[n] = '\0';
else if (size)
out[size-1] = '\0';
return n;
}
我的输出:
* 01 00 83 00 00 16 0a 44 00 00 00 00 bd 0e 8a 0c 61 01 13 51 24 ad 9a 0b 1c 0e ff ff 00
p* 00 83 00 00 16 0a 44 00 00 00 00 bd 0e 8a 0c 61 01 13 51 24 ad 9a 0b 1c 0e ff ff 00
这里我没有得到正确的输出,为什么打印了28bytes,这不是我想要的结果?
Trim: 16 0a 44 00 00 0 44 00 00 00 00 bd 0e 8a 0c 61 01 13 51 24 ad 9a 0b 1c 0e ff ff 00
最佳答案
您可以使用 memmove
,因为在 memcpy
中目标和源不能相互重叠,而在 memmove 中则无关紧要。所以你可以这样做
int offset = 11,size = 28;
memmove(buf, buf+off, size - off);
关于c - 无法使用 memcpy 从缓冲区中删除特定字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44257224/