Does this code authenticate?

I heard in little endian, LSB is at the start address, and in Big endian MSB is at the start address. I wrote my code as follows. If not?

void checkEndianess()
{

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

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


}
+3
source share
3 answers

No, you take an int and drop it to char, which is a high-level concept (and most likely this will be done in most registers). This has nothing to do with content, which is a concept that mainly relates to memory.

You are probably looking for:

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

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

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

#include <iostream>

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

/ , .: -)

+2

Try this instead:

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

Source: https://habr.com/ru/post/1761661/


All Articles