I'm trying to swap bytes for an assignment, and I thought this would be the way to do it.
p points to the scalar object to be reversed size is the number of bytes of the object.
void *ReverseEndian(void *p, size_t size)
{
char *head = (char *)&p;
char *tail = head + size - 1;
for (; tail > head; --tail, ++head) {
char temp = *head;
*head = *tail;
*tail = temp;
}
return p;
}
Is there something obviously wrong witht he above? I get an error with my professor's test code:
#define TestIt(a, b) TestReverse((void *)&(a),\
ReverseEndian((void *)&(b), sizeof(b)), sizeof(b))
int main()
char ch = 0x01, ch1 = ch;
short sh = 0x0123, sh1 = sh;
long lo = 0x01234567, lo1 = lo;
float fl = 1234.567e27F, fl1 = fl;
double db = 123456.567890, db1 = db;
long double ld = 987654.321053e-204L, ld1 = ld;
void *vp = (void *)0x0123, *vp1 = vp;
char *cp = (char *)0x4567, *cp1 = cp;
char *ip = (char *)0x89AB, *ip1 = ip;
TestIt(ch1, ch);
TestIt(sh1, sh);
TestIt(lo1, lo);
TestIt(fl1, fl);
TestIt(db1, db);
TestIt(ld1, ld);
TestIt(vp1, vp);
TestIt(cp1, cp);
TestIt(ip1, ip);
printf("ReverseEndian succeeded!\n");
return EXIT_SUCCESS;
}
void TestReverse(const void *before, const void *after, size_t size)
{
const char *cpBfore = (const char *)before;
const char *cpAfter = (const char *)after;
const char *tail;
for (tail = cpBfore + (size - 1); size; --size)
if (*tail-- != *cpAfter++)
{
fprintf(stderr, "ReverseEndian failed!\n");
exit(EXIT_FAILURE);
}
}