反向字节为64位值 [英] Reverse bytes for 64-bit value
问题描述
我正在尝试为分配分配64位地址指针的字节,并使用以下代码:
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;
}
但是,这只会弄乱一切。但是,类似的功能可以在64位长的情况下完美运行。指针有什么需要做的吗?
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?
对于指针:
*(char*)loc = swapPtr(*(char*)loc);
很长一段时间:
*loc = swapLong(*loc);
推荐答案
您不能使用 char x
为指针!!!! char
只有一个字节长。
You cannot use char x
for a pointer!!!! A char
is only a single byte long.
您至少需要
unsigned long int swapPtr(unsigned long int x) {
或者更好,使用指针的类型
Or better, use the type of the pointer
void* swapPtr(void* x) {
当您开始移动指针时,编译器很可能会抱怨;在这种情况下,最好将参数显式转换为无符号的64位整数:
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:
#include <stdint.h>
uint64_t x;
还请注意,您必须使用变量地址进行调用,因此您必须使用
Note also that you have to call with the address of a variable, so you call with
result = swapLong(&loc);
不是 * loc
(在 loc
指向的地方-值,而不是地址)。
not *loc
(which looks at the place where loc
is pointing - the value, not the address).
完整程序:
#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));
}
输出:
the address of a is 0x00007fff6b133b1b
swapping all the bytes gives 0x1b3b136bff7f0000
编辑,您可以使用类似的
#include <inttypes.h>
printf("the address of a is 0x%016" PRIx64 "\n", (uint64_t)(&a));
其中,宏 PRIx64
扩展为您需要以十六进制格式打印64位数字的格式字符串。比上面的清洁一点。
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.
这篇关于反向字节为64位值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!