基本上我有一个十进制值的硬编码地址,我想将其转换为指针,我一直在关注这个link
但我没有让它运行,因为我相信我的地址被截断,即地址中的 0 被删除。
有什么方法可以维护 0,或者有没有办法可以将 buff
中存储的地址类型转换为指针?
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[]) {
int address = 200000000;
char buff[80];
sprintf(buff, "0x%012x", address);
printf("%s\n", buff);
uint32_t * const Value = (uint32_t *)(uintptr_t)buff;
// *Value = 10;
printf("%p\n", Value); // Value is now storing the value of the variable buff, I dont want this
uint32_t *const Value2 = (uint32_t *)(uintptr_t)0x00000bebc200;
printf("%p\n", Value2); // my address gets truncated, dont want the address to be truncated
}
最佳答案
如果 %p
仅显示 8 个十六进制数字的地址,那么这是因为您平台上的指针只有 32 位,在这种情况下,前导零没有任何意义,因为没有地址总线 A32 至 A40 设置为零。这些位没有被“截断”,它们并不在最初的位置。
如果您出于某种奇怪的原因希望在 32 位就足够的平台上将地址显示为 48 位(12 个十六进制数字),那么:
uintptr_t address = 200000000u ;
uint32_t* const Value = (uint32_t *)address ;
printf( "0x%12.12lX\n", (uintptr_t)Value ) ;
输出:
0x00000BEBC200
但这只是表示问题,address
和 Value
中的值没有改变,仍然是 32 位。
关于c - 向指针地址添加 0 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60239219/