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

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

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 function input 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 that the function only changes the first half of the input, and I don't know what is going on with the second half.

I wrote another function called "int swapInt (int x)" using a similar idea with swapLong () and it works great ... so I don't know what I did wrong for swapLong ()

+3


source to share


4 answers


You can use sizeof(long)

instead 8

.



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

      

+3


source


Your code works fine on my system with your input. I'm sure yours is 32 bit long.

I am not allowed to edit my comment after 5 minutes, so I'll post it here.



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

+2


source


From what you described, you seem to be ignoring the warning you get for a truncated constant value

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

since your long strings only look 32bit.

Use sizeof()

in your loop instead 8

and it should work fine.

at the beginning of your program, you can write

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

      

+1


source


Find 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;
}

      

0


source







All Articles