64位值的反转字节

nix*_*nix 7 c reverse byte swap endianness

我正在尝试为分配转换64位地址指针的字节,并使用以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

对于指针:

*(char*)loc = swapPtr(*(char*)loc);
Run Code Online (Sandbox Code Playgroud)

很久了:

*loc = swapLong(*loc);
Run Code Online (Sandbox Code Playgroud)

Flo*_*ris 8

你不能用char x指针!!!! A char只有一个字节长.

你需要至少

unsigned long int swapPtr(unsigned long int x) {
Run Code Online (Sandbox Code Playgroud)

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

void* swapPtr(void* x) {
Run Code Online (Sandbox Code Playgroud)

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

#include <stdint.h>
uint64_t x;
Run Code Online (Sandbox Code Playgroud)

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

result = swapLong(&loc);
Run Code Online (Sandbox Code Playgroud)

not *loc(查看loc指向的地方- 值,而不是地址).

完整计划:

#include <stdio.h>
#include <stdint.h>

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));
}
Run Code Online (Sandbox Code Playgroud)

输出:

the address of a is 0x00007fff6b133b1b
swapping all the bytes gives 0x1b3b136bff7f0000
Run Code Online (Sandbox Code Playgroud)

编辑你可以使用类似的东西

#include <inttypes.h>

printf("the address of a is 0x%016" PRIx64 "\n", (uint64_t)(&a));
Run Code Online (Sandbox Code Playgroud)

其中宏PRIx64扩展为"您需要以十六进制打印64位数字的格式字符串".它比上面的一点清洁.

  • 只是不要使用固定宽度类型来执行此类任务.适当的类型是`uintptr_t`.另外你可以"`#if UINTPRT_SIZE> UINT32_SIZE`"这个假设宽度是64位的部分. (3认同)
  • 次要:考虑 `printf("0x016" PRIx64, (uint64_t)(&amp;a))` 或 `printf("0x%016llx\n", (unsigned long long)(&amp;a))` 而不是发布的获取格式和要匹配的整数? (2认同)