Link to home
Start Free TrialLog in
Avatar of Shinjji
Shinjji

asked on

Byte swapping a double in C / C++

Hi, im converting a program from a silicon graphics machine to the PC.

I would like to know how to byte swap a double

I have tried the following but it doesnt seem to work :-

-----------------------------------------------
void byteSwapDouble(double *ptrValue)
{
     double  *ptrTemp;
     char * swapA, swapB;

     ptrTemp = ptrValue;
     swapA = (char *)ptrTemp;

     swapB = swapA[0];
     swapA[0] = swapA[7];
     swapA[7] = swapB;
     swapB = swapA[1];
     swapA[1] = swapA[6];
     swapA[6] = swapB;
     swapB = swapA[2];
     swapA[2] = swapA[5];
     swapA[5] =swapB;
     swapB = swapA[3];
     swapA[3] = swapA[4];
     swapA[4] = swapB;

     ptrTemp = (double *)swapA;
     ptrValue = ptrTemp;
}
----------------------------------------

Avatar of Kocil
Kocil

#define swapByte(a, b, t) t=*(a); *(a)=*(b); *(b)=t

void byteSwapDouble(double *ptrValue)
{
    char temp;
    swapByte(ptrValue, ptrValue+7, temp);
    swapByte(ptrValue+1, ptrValue+6, temp);
    swapByte(ptrValue+2, ptrValue+5, temp);
    swapByte(ptrValue+3, ptrValue+4, temp);
}
ASKER CERTIFIED SOLUTION
Avatar of Kocil
Kocil

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Shinjji

ASKER

Good stuff.