Types of endianness

后端 未结 8 1247
情话喂你
情话喂你 2020-12-04 22:57

What is the difference between the following types of endianness?

  • byte (8b) invariant big and little endianness
  • half-word (16b) invariant big and litt
8条回答
  •  旧巷少年郎
    2020-12-04 23:34

    Practically speaking, endianess refers to the way the processor will interpret the content of a given memory location. For example, if we have memory location 0x100 with the following content (hex bytes)

    
      0x100:  12 34 56 78 90 ab cd ef
    
    Reads    Little Endian            Big Endian
     8-bit:  12                        12
    16-bit:  34 12                     12 34
    32-bit:  78 56 34 12               12 34 56 78
    64-bit:  ef cd ab 90 78 56 34 12   12 34 56 78 90 ab cd ef
    

    The two situations where you need to mind endianess are with networking code and if you do down casting with pointers.

    TCP/IP specifies that data on the wire should be big endian. If you transmit types other than byte arrays (like pointers to structures), you should make sure to use the ntoh/hton macros to ensure the data is sent big endian. If you send from a little-endian processor to a big-endian processor (or vice versa), the data will be garbled...

    Casting issues:

    
     uint32_t* lptr = 0x100;
     uint16_t  data;
     *lptr = 0x0000FFFF
    
     data = *((uint16_t*)lptr);
    

    What will be the value of data? On a big-endian system, it would be 0 On a little-endian system, it would be FFFF

提交回复
热议问题