I'm trying to reverse the bytes for a 64 bit address pointer for an assignment and have this code:
char swapPtr(char x){
x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32;
x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16;
x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8;
return x;
}
But, it just messes everything up. However, a similar function works perfectly for a 64bit long. Is there something different that needs to be done for pointers?
Could the way I'm making the function call be an issue?
For a pointer:
*(char*)loc = swapPtr(*(char*)loc);
For a long:
*loc = swapLong(*loc);
Here is an alternative way for converting a 64-bit value from LE to BE or vice-versa.
You can basically apply this method any type, by defining
var_type
:Reverse by pointer:
Reverse by value:
You cannot use
char x
for a pointer!!!! Achar
is only a single byte long.You need at the very least
Or better, use the type of the pointer
Quite likely your compiler will complain when you start bit shifting pointers; in that case you're better off explicitly casting your argument to an unsigned 64 bit integer:
Note also that you have to call with the address of a variable, so you call with
not
*loc
(which looks at the place whereloc
is pointing - the value, not the address).Complete program:
Output:
EDIT you could use something like
where the macro
PRIx64
expands into "the format string you need to print a 64 bit number in hex". It is a little cleaner than the above.