繁体   English   中英

此代码是否检查endianess?

[英]Does this code check for endianess?

我在小端看到,LSB处于起始地址,在Big endian中,MSB处于起始地址。 所以我写了这样的代码。 如果不是为什么?

void checkEndianess()
{

int i = 1;
char c = (char)i;

if(c)
        cout<<"Little Endian"<<endl;
else
    cout<<"Big Endian"<<endl;


}

不,您正在使用int并将其转换为char,这是一个高级概念(内部最有可能在寄存器中完成)。 这与字节序无关,字节序主要与记忆有关。

你可能正在寻找这个:

int i = 1;
char c = *(char *) &i;

if (c) {
   cout << "Little endian" << endl;
} else {
   cout << "Big endian" << endl;
}

(可以说,当然;-P)更清晰地获取相同内存的不同解释的方法是使用联合:

#include <iostream>

int main()
{
    union
    {
        int i;
        char c;
    } x;
    x.i = 1;
    std::cout << (int)x.c << '\n';
}

BTW /有更多的字节序变化而不仅仅是大而小。 :-)

试试这个:

int i = 1;
if (*(char *)&i)
    little endian
else
    big endian

暂无
暂无

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

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