64位值的反转字节

我正在尝试为分配反转64位地址指针的字节并具有以下代码:

char swapPtr(char x){ x = (x & 0x00000000FFFFFFFF) <> 32; x = (x & 0x0000FFFF0000FFFF) <> 16; x = (x & 0x00FF00FF00FF00FF) <> 8; return x; } 

但是,它只是让一切都搞砸了。 但是,类似的function适用于64位长。 是否需要针对指针做一些不同的事情?

我正在进行函数调用的方式是一个问题吗?

对于指针:

 *(char*)loc = swapPtr(*(char*)loc); 

很久了:

 *loc = swapLong(*loc); 

你不能使用char x作为指针!!!! char只有一个字节长。

你需要至少

 unsigned long int swapPtr(unsigned long int x) { 

或者更好,使用指针的类型

 void* swapPtr(void* x) { 

当您开始移位指针时,您的编译器很可能会抱怨; 在这种情况下,最好将显式转换为无符号的64位整数:

 #include  uint64_t x; 

另请注意,您必须使用变量的地址进行调用,因此请使用

 result = swapLong(&loc); 

not *loc (查看loc指向的位置 – 值,而不是地址)。

完整计划:

 #include  #include  uint64_t swapLong(void *X) { uint64_t x = (uint64_t) X; x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32; x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16; x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8; return x; } int main(void) { char a; printf("the address of a is 0x%016llx\n", (uint64_t)(&a)); printf("swapping all the bytes gives 0x%016llx\n",(uint64_t)swapLong(&a)); } 

输出:

 the address of a is 0x00007fff6b133b1b swapping all the bytes gives 0x1b3b136bff7f0000 

编辑你可以使用像

 #include  printf("the address of a is 0x%016" PRIx64 "\n", (uint64_t)(&a)); 

其中宏PRIx64扩展为“您需要以hex格式打印64位数字的格式字符串”。 它比上面的一点清洁。

以下是将64位值从LE转换为BE的替代方法,反之亦然。

您基本上可以通过定义var_type将此方法应用于任何类型:

 typedef long long var_type; 

通过指针反转:

 void swapPtr(var_type* x) { char* px = (char*)x; for (int i=0; i 

按价值反转:

 var_type swapVal(var_type x) { var_type y; char* px = (char*)&x; char* py = (char*)&y; for (int i=0; i