Search code examples
cpointersbyte-shifting

function that takes a long value and returns with its bytes in reverse order in C


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()


Solution

  • 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]; 
    }
    ...