There is a variable of type signed short
. It is necessary to drive it into an unsigned char
array, for further transmission over the network.
How to do it?
- And here comes the question of the arhitecture (big endian - little endian). Most of all, the comment of @avp is pleasant - with this approach these problems are already taken into account. - alexlz
|
1 answer
Select the appropriate buffer size char, take a pointer to our data, bring it to the target type, mixing the pointer, copy the data to the buffer. Well, the buffer is a helmet. At the "that end" the inverse operation, if we consider the size of sizeof (signed short) equal on both machines.
signed short some_val = 333; unsigned char* cbuffer = new unsigned char[sizeof(signed short)]; unsigned char* pointer_to_value = reinterpret_cast<unsigned char*>(&some_val); for (size_t i=0; i<sizeof(signed short); ++i) { cbuffer[i] = pointer_to_value[i]; } delete [] cbuffer;
- oneDon't forget about
hton*
yet. - VladD - Or it can be easier #include <string.h> #include <arpa / inet.h> .... char cbuffer [YOUR_BUFFER_SIZE], * pc = cbuffer; short short_to_send, ts; ..... ts = htons (short_to_send); memcpy (pc, & ts, sizeof (ts)); pc + = sizeof (ts); // this is for filling the rest of the buffer. Although this is C code, g ++ does not swear. - avp
|