Search code examples
c++visual-c++endianness

compiler and endians


I have an ISA which is "kind" of little endian. The basic memory unit is an integer and not byte.For example

00000000: BEFC03FF 00008000

Represents that the "low" integer is BEFC03FF and "high" integer is 00008000. I need to read the value represented by some bits.For example bits 31 till 47. What I am doing in VS10 (c++) generate uint64_t var = 0x00008000BEFC03FF after it use relevant mask and check the value of var & mask. Is it legal to do that way?I do some assumption about uint64_t bits arrangement - is it legal? Can I suppose that for very compiler and for every OS (without dependency on hw) the arrangement of bits in the uint64_t will be this way?


Solution

  • You are right to be concerned, It does matter.

    However, in this particular case, since ISA is little endian, i.e. if it has AD[31:0], the least significant bit of an integer is packed to bit 0. Assuming your processor is also little endian, then nothing to worry about. when the data written to memory, it should have the right byte order

    0000  FF
    0001  03
    0002  ..
    

    suppose, if your external bus protocol is big endian and your processor is little endian. then a 16 bit integer in your processor, say 0x1234 would be 0001_0010_0011_0100 in native format, but 0010_1100_0100_1000 on the bus (assuming it's 16 bit).

    In this case, multi byte data crosses endian boundary, the hardware will only swap bits inside a byte, because it must preserve the memory contiguousness between bytes. after hardware swap, it becomes:

    0000 0001_0010
    0001 0011_0100
    

    then it is up to the software to swap the byte order