Does this code check for endianess?

回眸只為那壹抹淺笑 提交于 2019-12-13 14:16:24

问题


I heard in little endian, the LSB is at starting address and in Big endian MSB is at starting address. SO I wrote my code like this. If not why ?

void checkEndianess()
{

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

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


}

回答1:


No, you're taking an int and are casting it to a char, which is a high-level concept (and will internally most likely be done in registers). That has nothing to do with endianness, which is a concept that mostly pertains to memory.

You're probably looking for this:

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

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



回答2:


An (arguably, of course ;-P) cleaner way to get distinct interpretations of the same memory is to use a union:

#include <iostream>

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

BTW / there are more variations of endianness than just big and little. :-)




回答3:


Try this instead:

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


来源:https://stackoverflow.com/questions/3572371/does-this-code-check-for-endianess

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!