C中的Printf打印ffffffe1而不是e1

时间:2018-01-28 02:25:51

标签: c

我非常困惑,我有一个小程序,我在不同的地址位置打印值。

int main ()
{
 // unsigned int x = 0x15711056;
  unsigned int x = 0x15b11056;
  char *c = (char*) &x;

  printf ("*c is: 0x%x\n", *c);
  printf("size of %d\n", sizeof(x));
  printf("Value at first address %x\n", *(c+0));
  printf("Value at second address %x\n", *(c+1));
  printf("Value at third address %x\n", *(c+2));
  printf("Value at fourth address %x\n", *(c+3));

对于带注释的unsigned int x,printf值是预期的,即

  printf("Value at first address %x\n", *(c+0)) = 56
  printf("Value at second address %x\n", *(c+1))= 10
  printf("Value at third address %x\n", *(c+2))= 71
  printf("Value at fourth address %x\n", *(c+3))= 15

但是对于未注释的int x为什么我的结果低于*(c + 2)它应该是 b1 而不是 ffffffb1 。请帮助我理解这一点,我在在线IDE https://www.onlinegdb.com/online_c_compiler上运行它。我的电脑是i7 intel。

  printf("Value at first address %x\n", *(c+0)) = 56
  printf("Value at second address %x\n", *(c+1))= 10
  printf("Value at third address %x\n", *(c+2))= ffffffb1
  printf("Value at fourth address %x\n", *(c+3))= 15

3 个答案:

答案 0 :(得分:2)

该值在二进制文件中以0xB110110001进行签名,您需要使用unsigned char指针:

unsigned char *c = (unsigned char*) &x;

您的代码适用于0x7F之前的任何字节。

答案 1 :(得分:2)

csigned char0xB1(已签名)是1011 0001,你看到了 最重要的位是1,所以它是负数。

当您将*(c+2)传递给printf时,它会被提升为int 签。符号扩展使用与其相同的值填充其余位 来自char的最重要位,即1. {此时printf 得到1111 1111 1111 1111 1111 1111 1011 0001

%x中的

printf将其打印为unsigned int,因此会打印0xFFFFFFB1

您必须将指针声明为unsigned char

unsigned char *c = (unsigned char*) &x;

答案 2 :(得分:1)

unsigned int x = 0x15b11056; /*lets say starting address of x is 0x100 */
char *c = (char*) &x; /** c is char pointer i.e at a time it can fetch 1 byte and it points to 0x100 **/

x如下所示

  ------------------------------------------------------
  | 0001 0101  |  1011 0001  |  0001 0000  |  0101 0110 |
   ------------------------------------------------------
0x104         0x103         0x102         0x101        0x100
                                                        x
                                                        c

接下来,当您正在进行*(c+2));时,请将其展开

*(c+2)) = *(0x100 + 2*1) /** increment by 1 byte */
           = *(0x102)
           =  1011 0001 (in binary) Notice here that sign bit is 1 
              means sign bit is going to copy to remaining bytes 

当您以%x格式打印,期望unsigned typecsigned字节时,sign bit会被复制到剩余字节中。

*(c+2)输入的

看起来像

 0000 0000  |  0000 0000  |  0000 0000  |  1011 0001
                                                |
                                            sign bit is one so this bit will be copied into remaining bytes, resultant will look like below
 1111 1111  |  1111 1111   |  1111 1111  |  1011 0001  
  f     f       f    f          f    f        b   1

我解释了你怀疑的特定部分,我希望它有所帮助。