简体   繁体   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

why the -1078061268 in dec is not equal 0xbfbe172c in hex? 为什么-1078061268 12月不等于0xbfbe172c十六进制?

it is. 它是。 in 2's complement. 以2的补码形式

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

An address is not an int. 地址不是整数。 if your machine is 32bit, it is an unsigned int (in fact, uint32_t ). 如果您的计算机是32位的,则它是一个无符号的int(实际上是uint32_t )。 if not, it is a uint64_t . 如果不是,则为uint64_t it is always safe to put it in a uintptr_t , and print it with %p . 始终将其放在uintptr_t ,并使用%p打印。

They are the same, you're comparing signed to unsigned. 它们是相同的,您正在比较带符号的和无符号的。

take a look here at the formats. 这里看看格式。

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

The first printf statement is treating the address as a signed integer. 第一条printf语句将地址视为有符号整数。 The second is treating it is a pointer (which, for printf, amounts to printing it out as an unsigned hex number). 第二个方法是将其视为一个指针(对于printf,相当于将其打印为无符号十六进制数字)。 Those two numbers have the same binary representation in two's complement arithmetic, although they are not numerically equal. 这两个数字在二进制补码算法中具有相同的二进制表示形式,尽管它们在数值上不相等。 This is why comparisons between signed and unsigned values are a bad idea. 这就是为什么在有符号值和无符号值之间进行比较是个坏主意的原因。

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

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