简体   繁体   English

将32位指针转换为64位整数

[英]convert 32-bit pointer to 64-bit integer

What's the best way to do this? 最好的方法是什么?

Say I have: 说我有:

 void* p = 0xc8f68000;
 unsigned long long v = (unsigned long long)p;

I got v = 0xffffffffc8f68000 instead of 0x00000000c8f68000. 我得到v = 0xffffffffc8f68000而不是0x00000000c8f68000。 Do I have to use shift? 我必须使用班次吗?

Whenever you deal with pointer to integer conversions, it's best to use uintptr_t . 每当处理整数转换的指针时,最好使用uintptr_t It is the portable way to avoid size and sign extension issues when casting pointers. 这是在投射指针时避免大小和符号扩展问题的可移植方法。

#include <stdint.h>

void *p = 0xc8f68000;
uint64_t v = (uintptr_t)p;

What seems to be happening is that 0xc8f68000 is being treated as a signed 32 bit integer, and then being converted to unsigned. 似乎正在发生的事情是0xc8f68000被视为有符号的 32位整数,然后被转换为无符号。 You should get the 'correct' value with: 您应该通过以下方式获得“正确”值:

void* p = 0xc8f68000;
unsigned long long v = (unsigned long)p;

or probably better: 也许更好:

void* p = 0xc8f68000;
unsigned long long v = (size_t)p;

since the latter isn't dependent on p actually being 32 bits. 因为后者实际上并不依赖于p是32位。

I question why you want to do this, however. 我质疑您为什么要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM