查找尾序指针类型转换的代码

Code to find Endianness-pointer typecasting

本文关键字:代码 类型转换 指针 查找      更新时间:2023-10-16

我试图搜索一个代码来确定系统的端序,这就是我发现的:

int main()
{
    unsigned int i= 1;
    char *c = (char *)&i;
    if (*c) {
        printf("Little Endiann");
    } else {
        printf("Big Endiann");
    }
}

谁能告诉我这个代码是如何工作的?更具体地说,为什么在这个类型转换中需要&符号:

char *c = (char *)&i;

指针c中存储了什么?是I所包含的值还是I所包含的实际地址?为什么这个是这个程序的字符?

在解引用字符指针时,只解释一个字节(假设char变量占用一个字节)。在little-endian模式下,首先存储整数的least-significant-byte。对于一个4字节的整数,比如3,它被存储为

00000011 00000000  00000000  00000000

而对于big-endian模式,它被存储为:

00000000  00000000  00000000  00000011

所以在第一种情况下,char*解释第一个字节并显示3,但在第二种情况下,它显示0

如果你没有将它类型化为:

char *c = (char *)&i;

将显示一个关于不兼容的指针类型的警告。如果cinteger pointer,对其解引用将得到一个整数值3,而不考虑端序,因为所有4个字节都将被解释。

NB您需要初始化变量i才能看到整个画面。否则,默认情况下将在变量中存储一个垃圾值。

警告! ! OP,我们讨论了little-endianbig-endian之间的区别,但更重要的是要知道little-endianlittle-indian之间的区别,我注意到您使用了后者。好吧,不同的是,little-indian可能会让你失去在谷歌的理想工作,或者如果你的面试官是Nikesh Arora,Sundar Pichai,Vinod Dham or Vinod Khosla的话,会让你失去300万美元的风险投资:-)

让我们试着看一下这个:

int main(void){ /
  unsigned int i = 1;    // i is an int in memory that can be conceptualized as 
                         // int[0x00 00 00 01]
  char *c = *(char *)&i; // We take the address of i and then cast it to a char pointer
                         // which we then dereference. This cast from int(4 bytes) 
                         // to char(1 byte) results in only keeping the lowest byte by
  if(*c){                // Endian-ness. 
    puts("little!n");   // This means that on a Little Endian machine, 0x01 will be 
  } else {               // the byte kept, but on a Big Endian machine, 0x00 is kept.
    puts("big!n");      // int[0x00 00 00 (char)[01]]  vs  int[0x01 00 00 (char)[00]]
  }
  return 0;
}