質問

Apparently it seems Ideone and Codepad both uses Little endian to compile and run their code.

If for example I want to test the following on Big endian CPU then I'm curious to know does casting the unsigned char[] array to unsigned short* really changes its output?

#include <iostream>

int main()
{
   unsigned char a[2] = {0, 1};
   unsigned short *s = (unsigned short*)a;
   std::cout << *s;
}

As far as I have known that if you cast an int to char* then it does depend on the endianness but what is case with arrays or any other type you try to reinterpret?

http://ideone.com/4UP0J0

役に立ちましたか?

解決

Endian is a feature of the CPU, not the compiler...

Assuming your short type if 16 bits, and the unsigned chars are 8 bits then the memory layout of a will be

0x00 0x01

On a bit endian CPU this means that *s will be 1 (0x0001). On a little endian CPU *s will be 256 (0x0100).

As an aside, it's not so easy to find big endian CPUs any more. This page has a list of CPU architectures from the last few decades and lists the endianness of each one.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top