Domanda

I am doing a homework that requires me to write a function that takes a long value and returns with its bytes in reverse order in C, the prototype for the function is given, which is

long swapLong(long x)

and my code looks like this :

long swapLong(long in)
{
    long out;
    char *inp = (char *) &in ;
    char *outp = (char *) &out;

    int i=0;
    for (i=0; i<8 ;i++)
    {    
        outp[i] = inp[7-i]; 
    }

    return out;
} 

if the input of the function is 0x1122334455667788

it should return 0x8877665544332211

however, when i test it with

long test2 = 0x1122334455667788;
long result2= swapLong(test2);
printf("0x %lx\n", test2);
printf("0x %lx\n", result2);

the result is 0x44332211

it seems like the function only swaps the first half oh the input and I don't know what happens to the second half

I have write another function called " int swapInt( int x) ", using similar idea with swapLong() and it works great.... so I dont know what did I do wrong for swapLong()

È stato utile?

Soluzione

You might like to use sizeof(long)instead of 8.

...
size_t i;
size_t sizeLong = sizeof(long);
for (i=0; i<sizeLong ;i++)
{    
    outp[i] = inp[sizeLong-i-1]; 
}
...

Altri suggerimenti

Your code works fine on my system with your given input. I am pretty sure your long is 32 bits.

I am not allowed to edit my comment after 5 minutes so i will write it here.

C ensures that int must be at least as big as short and long must be atleast big as int. So your compiler chooses the best size based on the target platform (processor).

From what you describe you seem to be ignoring a warning you get for truncated constant value

long test2 = 0x1122334455667788; // 1234605616436508552 > 2^32-1

since your longs appear to be only 32-bit.

Use sizeof() in your loop instead of 8 and it should work fine.

at the start of your program you could write

assert( sizeof(long) == 4 ); // to see if it is 32-bit or not.

Work out what's going on here for further enlightenment:

long swapLong(long x)
{
    int s = sizeof(long);
    long r = 0;
    for(int i=0; i<s; ++i)
    {
        r <<= 8;
        r |= x & 0xff;
        x >>= 8;
    }
    return r;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top