I have a buffer with n bytes, but I only want read in sizeof(something) bytes from byte 3, meaning I don't want to read in byte 1 and 2 from the buffer. For example...
For some buffer, byte 1 = 'a', byte 2 = 'b', byte 3 = uint64_t variable. What I want to do is something like
1. set begin to byte 3
2. read in sizeof(uint64_t) bytes from buffer using memmove
First, a bit of clarification. C array indexing starts at 0, not 1, so it's more accurate to say that byte 0 is 'a'
and byte 1 is 'b'
. Second, your third byte, cannot contain a uint64_t
variable, but index 2 may well be the beginning of a uint64_t
object.
No, there is no lseek
equivalent for memmove()
-- because, unlike file operations, a call to memmove()
must specify the starting point.
And in this case, you might as well use memcpy()
rather than memmove()
. The only difference between them is that memmove()
handles overlapping buffers correctly. Since your source and target are distinct objects, that's not a concern. It's not going to significantly affect your code's speed, but anyone reading it won't have to wonder why you chose to use memmove()
.
Given:
unsigned char buf[SOME_SIZE];
uint64_t target;
you can do something like this:
memcpy(&target, buf+2, sizeof target);
Note that I used sizeof target
rather than sizeof (uint64_t)
. Either will work, but using sizeof target
makes your code more resilient (less vulnerable to errors as you change it later on). If you decide to change the type of target
, you don't need to remember to change the type in the memcpy()
call.