我无法从我想要的大小中截断缓冲区。我有点困惑,为什么我得到错误的结果?尽管我对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
答案 0 :(得分:2)
你可以memmove
使用memcpy
,因为 int offset = 11,size = 28;
memmove(buf, buf+off, size - off);
目标和源不能相互重叠,而在memmove中它并不重要。所以你可以做到
{
"background": {
"persistent": true,
"scripts": [ "background.js" ]
},
"description": "This extension ...",
"manifest_version": 2,
"name": "Something",
"permissions": [ "webRequest", "webRequestBlocking", "http://*/*",
"https://*/*" ],
"version": "1",
"icons": {
"128": "msdos.png"
}
答案 1 :(得分:2)
memcpy
来电中的来源和目的地重叠。从标准:
如果在重叠的对象之间进行复制,则行为 未定义。
标准函数memmove
与memcpy
类似,但为重叠对象定义,请改用它。
答案 2 :(得分:0)
当您调用memcpy
时,您不会从缓冲区中复制字节。您正在复制&#34; hex_parsed&#34;串。由于该格式每个字节使用3个字符(2个数字和一个空格),因此砍掉11个字符会削减大约4个字节。