簡體   English   中英

為什么地址號的十進制和十六進制不相等?

[英]Why the address number is not equal in dec and in hex?

debian@debian:~$ cat  /tmp/test.c
#include<stdio.h> 
int  main(void)
{
 int m=1;
 printf("m=%d\n",&m);
 printf("m=%p\n",&m);
}
debian@debian:~$ gcc  /tmp/test.c -o  /tmp/test.exe
debian@debian:~$ /tmp/test.exe
m=-1078061268
m=0xbfbe172c
debian@debian:~$ python
Python 2.7.3 (default, Jan  2 2013, 16:53:07) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print hex(-1078061268)
-0x4041e8d4

為什么-1078061268 12月不等於0xbfbe172c十六進制?

它是。 以2的補碼形式

>>> hex(2**32-1078061268)
'0xbfbe172c'

地址不是整數。 如果您的計算機是32位的,則它是一個無符號的int(實際上是uint32_t )。 如果不是,則為uint64_t 始終將其放在uintptr_t ,並使用%p打印。

它們是相同的,您正在比較帶符號的和無符號的。

這里看看格式。

#include<stdio.h> 
int  main(void)
{
   int m=1;
   printf("m=%u\n",&m);  // 3219008780
   printf("m=%p\n",&m);  // 0xbfde2d0c
}

第一條printf語句將地址視為有符號整數。 第二個方法是將其視為一個指針(對於printf,相當於將其打印為無符號十六進制數字)。 這兩個數字在二進制補碼算法中具有相同的二進制表示形式,盡管它們在數值上不相等。 這就是為什么在有符號值和無符號值之間進行比較是個壞主意的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM