Worth going through the effort with Xcode 2.5?

Moderator
Posts: 1,560
Joined: 2003.10
Post: #31
It'll work for longs if you're compiling only a 32-bit binary, but a better solution is to use the types defined in stdint.h (uint32_t, etc.) that are guaranteed to be a particular size regardless of architecture. This way, you don't need to think about having a swap function for a short, an int, and a long, but rather having one for a 16-bit integer, a 32-bit integer, and a 64-bit integer.

Something like this should work:

Code:
#define swapInt16(int16) ((((int16) >> 8) & 0x00FF) | \
                          (((int16) << 8) & 0xFF00))

#define swapInt64(int64) ((((int64) >> 56) & 0x00000000000000FF) | \
                          (((int64) >> 40) & 0x000000000000FF00) | \
                          (((int64) >> 24) & 0x0000000000FF0000) | \
                          (((int64) >> 8)  & 0x00000000FF000000) | \
                          (((int64) << 8)  & 0x000000FF00000000) | \
                          (((int64) << 24) & 0x0000FF0000000000) | \
                          (((int64) << 40) & 0x00FF000000000000) | \
                          (((int64) << 56) & 0xFF00000000000000))
Quote this message in a reply
Luminary
Posts: 5,143
Joined: 2002.04
Post: #32
you'll need some "ull" suffixes in there I think...
Quote this message in a reply
Member
Posts: 353
Joined: 2002.04
Post: #33
Seems to be working for ints of different sizes, thanks. The other issue is floats. I did some searching and found this code from an old iDevGames post:

Code:
float floatSwap(char *value)
{
char buffer[ 4 ];

buffer[ 0 ] = value[ 3 ];
buffer[ 1 ] = value[ 2 ];
buffer[ 2 ] = value[ 1 ];
buffer[ 3 ] = value[ 0 ];

return *( (float *) &buffer );
}

Which seems to work alright. Any reason why this would not be an advisable method?
Sorry for all the questions, when it comes to things like endianess and byte swapping the graphic designer/non-programmer comes out in me. Smile
Quote this message in a reply
Moderator
Posts: 1,560
Joined: 2003.10
Post: #34
Should work fine. You could also do a non-converting typecast to uint32_t, swap, then convert back.

Code:
float swapMe;
uint32_t temp;

temp = *(uint32_t *) &swapMe;
swapInt32Big(temp);
swapMe = *(float *) &temp;
Quote this message in a reply
Member
Posts: 353
Joined: 2002.04
Post: #35
All working now, cheers guys!
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Worth the trouble? NelsonMandella 7 4,053 Feb 7, 2010 05:48 PM
Last Post: cmiller