查找尾序指针类型转换的代码
Code to find Endianness-pointer typecasting
我试图搜索一个代码来确定系统的端序,这就是我发现的:
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;
将显示一个关于不兼容的指针类型的警告。如果c
是integer pointer
,对其解引用将得到一个整数值3
,而不考虑端序,因为所有4个字节都将被解释。
NB您需要初始化变量i
才能看到整个画面。否则,默认情况下将在变量中存储一个垃圾值。
警告! ! OP,我们讨论了little-endian
和big-endian
之间的区别,但更重要的是要知道little-endian
和little-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;
}
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 将类指针类型转换为键时出错
- 关于使用类型转换优化除法代码的问题
- 在以下代码中如何完成类型转换
- 为什么隐式类型转换在此代码中结果不正确
- 为什么我的代码不使用类型转换进行编译?
- 这段c++类型转换代码在做什么?
- 如何将c++联合类型转换为c#代码
- 查找尾序指针类型转换的代码
- C++类型转换运算符代码,在 Visual Studio 2012 中无法编译,但在 Visual Studio 2005 中工作正常
- 为什么它会在 arduino uno 代码中将错误:预期的构造函数、析构函数或类型转换放在"void"之前?
- 你认为是什么让这个C++代码变慢了?(它循环通过ADODB记录集,将COM类型转换为字符串,并填充ostringstre