Quote:
Originally Posted by kevin_owner
actually I want to copy the value into that array cause that's the way I build the packet. the reason i'm using this is cause i didn't find another way yet cause this one works fine for me.
Look my packet writer has a member which is currentPosition which i'm using for the index in that char array. so when I add a value lets say a short but it could also be a int I increase the currentPosition with the size of an int or short so it doesn't overwrite some data.
I'm sure that there will be an easier way and that it'll confuse some people and i have to admit that i went way to far in the code. Sorry for that:P
but would you mind telling me how you would build a packet to send cause that's the only way I know and i'd like to know more/better ways:)?
|
Yes, if you actually want to copy the data, then you have to do it the way you are doing it, more or less. Given the code of yours, I would however suggest few slight modifications, just to polish it a bit. As I have (not) mentioned above, using brackets might be a bit slower than doing the incrementation of pointer; perhaps like this...
Code:
*(int*)(buffer + position) = value;
However, my approach to this issue would be very different...consider this way of doing it.
Code:
/* i will take an assumption of the buffer being a lovely pointer monster... */
struct packet_buffer {
unsigned char *beg;
unsigned char *end;
unsigned char *cur;
};
/* and lets suppose we have some nice function that tries to append the
given value to the buffer. if that fails, NULL is returned... */
int packet_buffer_append(void *value, size_t len, struct packet_buffer *buf) {
if (buf->cur + len > buf->end)
return 0;
/* we could make use of the <string.h> function called <memcpy> which
would do the dirty work of copying data over;
memcpy(buf->cur, value, len);
/* increment the current position by <len> bytes of the data copied */
buf->cur += len;
/* just return something; why not pointer to current position in buffer? */
return buf->cur;
}
Anyway, maybe that kind of way is too C-ish, not modern enough nowadays, with all that C++ whatever rush.
Also, you should know that compilers have this nasty behaviour of aligning structures to fit certain number of bytes (well, usually to be multiple of the system
atomic size - e.g multiple of 4 or 8 bytes).
This means that if you have struct packet { short length, opcode, secure; char element; } it wont have 7 bytes but rather 8 bytes, with one byte stuck somewhere...