Reputation:
I m not able to truncate the buffer from the size what I want. I'm bit perplexed why I get wrong results? Even though my usage of memcpy() is right. I read the man page also. I'm doing something wrong here?
What I want to achieve:
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
Copy the bytes which start from bd, that means 12th bytes till the end-
Desired Output should be:
bd 0e 8a 0c 61 01 13 51 24 ad 9a 0b 1c 0e ff ff 00
This is my code: I'm receiving the response from serial device and I need chop some bytes.
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);
}
}
EDIT: Added the more details
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;
}
My ouutput:
* 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
Here I don't get the correct output, why is it prinitng 28bytes, this is not my desired result I wanted?
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
Upvotes: 0
Views: 421
Reputation: 20392
The source and destination in your memcpy
call overlap. From the standard:
If copying takes place between objects that overlap, the behavior is undefined.
The standard function memmove
is like memcpy
but defined for overlapping objects, use that instead.
Upvotes: 2
Reputation: 15803
You can use memmove
, as in memcpy
the target and the source must not overlap each other, while in memmove it does not matter. So you can do
int offset = 11,size = 28;
memmove(buf, buf+off, size - off);
Upvotes: 2
Reputation: 179927
When you're calling memcpy
, you're not copying the bytes from the buffer. You're copying the "hex_parsed" string. As that format uses 3 characters per byte (2 digits and a space), chopping 11 characters is chopping about 4 bytes.
Upvotes: 0