Little-endian and Big-endian

前端 未结 4 948
你的背包
你的背包 2021-01-27 17:43

I must write a routine for conversion between the 2 representations. But I\'m a bit confused. If I have an architecture with a memory with words of 32 bits and I must store the

相关标签:
4条回答
  • 2021-01-27 17:47

    Big-endian memory layout is most significant bytes first, whereas little-endian layout is least significant bytes first. Given the value 0xA15D23B1:

    Memory address    0  1  2  3
    Big-endian       A1 5D 23 B1
    Little-endian    B1 23 5D A1
    

    Note that big-endian memory layout does not change with respect to word size, but little-endian does. If you consider two short words (16 bit), 0xA15D and 0x23B1 stored contiguously:

    Memory address    0  1  2  3
    Big-endian       A1 5D 23 B1
    Little-endian    5D A1 B1 23
    
    0 讨论(0)
  • 2021-01-27 18:00
    • and in little-endian is 5D too?

    No. In little-endian it's 23

    0 讨论(0)
  • 2021-01-27 18:05

    There are various ways that processors implement big-endian and little-endian — for a detailed discussion, consult the Wikipedia article on Endianness.

    For a 2-byte quantity, there are just two options:

    Value:           0x1234 (MSB = 0x12, LSB = 0x34)
    Little-endian:   LSB then MSB    0x34  0x12  — Intel, …
    Big-endian:      MSB then LSB    0x12  0x34  — SPARC, PowerPC, …
    

    For a 4-byte quantity, there are more options, but there are still two primary ones (plus a historical curiosity):

    Value:           0x12345678 (MSB = 0x12, NMSB = 0x34, NLSB = 0x56, LSB = 0x78)
    Little-endian:   LSB, NLSB, NMSB, MSB    0x78  0x56  0x34  0x12
    Big-endian:      MSB, NMSB, NLSB, LSB    0x12  0x34  0x56  0x78
    PDP-11:          NMSB, MSB, NLSB, LSB    0x34  0x12  0x78  0x56
    

    Note that a number of modern chip sets are bi-endian — can be switched to run in big-endian or little-endian mode:

    Some architectures (including ARM versions 3 and above, PowerPC, Alpha, SPARC V9, MIPS, PA-RISC, SuperH SH-4 and IA-64) feature a setting which allows for switchable endianness in data segments, code segments or both.

    0 讨论(0)
  • 2021-01-27 18:11

    A good way to remember "which is which":

    Big-endian starts from the big (most-significant) end; little endian starts from the little end.

    For example, when regarding the word 0xA15D23B1 as a sequence of bytes, a big-endian machine starts it from the most significant byte 0xA1. It will be stored at the lowest address (this is the meaning of the potentially confusing word "start").

    By the way, if you only want to convert from big-endian to little-endian or back, you don't have to understand this: just reverse the order of bytes! This is why many people don't bother to understand what "big-endian" or "little-endian" means - you generally only need to understand whether or not to swap bytes.

    0 讨论(0)
提交回复
热议问题