I have a binary array char buffer[N]; which contains two bytes to be interpreted as an unsigned short at its beginning and am currently extracting those by doing
unsigned short size= 0;
memcpy((char *) &size, buffer, sizeof(unsigned short));
I would however like to use std::copy for this. Is this possible?
Attempts like
std::copy(buffer, buffer+sizeof(unsigned short), (char *) &size);
have resulted in various errors when compiling..
Edit: Sorry, I was in a hurry and forgot:
This is on a Ubuntu GNU/Linux system with gcc 4.4.3. The error message was Error: Invalid conversion from ‘char*’ to ‘char’.
You should not use any sort of bulk copy routine for this, nor should you use typecasting to get a pointer to
unsigned short, because none of those options take byte order into account. The correct way to extract a two-byte unsigned integer from achar[]buffer is with one of these functions:std::copy,memcpy, and direct pointer bashing will all do the same thing as one of these functions, but you don’t know which one it’ll be, and any time you have this task, one of these functions is right and the other one is wrong. Furthermore, if you don’t know which one of these you need from context, go up a couple design levels and figure it out.