Here's a quick tip that is useful if you are sending data over a network. If you ever messed with any sockets in programming then you know you can only send bytes of data. Why is this problem? Well, you can't exactly send over a 4 byte integer in a single 1 byte char. To get around this, we do something called packing.
char Buffer[4];
int Data = 1024;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
Buffer[0] = (Data >> 24) & 0xFF;
Buffer[1] = (Data >> 16) & 0xFF;
Buffer[2] = (Data >> 8) & 0xFF;
Buffer[3] = (Data) & 0xFF;
#elseif
Buffer[3] = (Data >> 24) & 0xFF;
Buffer[2] = (Data >> 16) & 0xFF;
Buffer[1] = (Data >> 8) & 0xFF;
Buffer[0] = (Data) & 0xFF;
#endif
Now, we can easily send over the Buffer char array. Two things to note here. First, depending on the system you are working on, the endianness can change (to read up on what endianness is, look here: http://en.wikipedia.org/wiki/Endianness) - that is what the #if SDL_BYTEORDER == SDL_BIG_ENDIAN statement is for. Secondly, we did nothing here to specify if the data being packed is signed or unsigned. You will need to know on the other end what type of data you are receiving.
Here's how you can unpack this data:
char Buffer[4];
int Data = 0;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
Data = ((((Uint8 *)Buffer)[0] << 24) | (((Uint8 *)Buffer)[1] << 16) | (((Uint8 *)Buffer)[2] << 8) | ((Uint8 *)Buffer)[3] << 0);
#elseif
Data = ((((Uint8 *)Buffer)[3] << 24) | (((Uint8 *)Buffer)[2] << 16) | (((Uint8 *)Buffer)[1] << 8) | ((Uint8 *)Buffer)[0] << 0);
#endif
union
{
char buffer[4];
int data;
} pack;
pack.data = 53398;
pack.buffer[0-3] now contain the same data.
Email (required, not published):
Website:
Don't do that, just pick one and stick with it. Incidentally, there are macros (ntohl, htonl = network-to-host and host-to-network) for byte order handling, so use htonl when packing and ntohl when unpacking, and just write the int as a 4-byte char-array.
Email (required, not published):
Website:
Email (required, not published):
Website:
Of what use is " & 0xFF". IMHO any data can be taken, ANDed with 0xFF (All ones) and stays the same. So isnt & 0xFF useless ?
Email (required, not published):
Website:
Email (required, not published):
Website:
could you explain how this works ?
because the >> operator doesn't seem to affect anything in that statement.
Email (required, not published):
Website:
Email (required, not published):
Website:
Email (required, not published):
Website:
Email (required, not published):
Website: