大端与小端 – Big Endian 和 Little Endian

掏出电脑搞事情,就会遇到“大端”(Big Endian, BE)和“小端”(Little Endian, LE)。

一、概念

涉及到大端还是小端的场景时,一般是两种设备之间进行通讯。为了形象说明,我们举例说明将十进制数字 1234567890 发送给另一台设备时的字节顺序。

十进制    : 1234567890
十六进制: 499602D2

假设地址偏移是由前到后由小到大的,那么:

MSB LSB
地址 0 1 2 3
大端 BE 49 96 02 D2
小端 LE D2 02 96 49

二、如何处理

目前来说,大端符合人的思维,并且网络字节也是采用大端顺序传输的。如果要改变传输顺序,可以人为进行赋值,例如 IEC61131-3 进行编程时:

CASE BytesOrder OF
    INT#1234:
        SendByteArray[BytesOrder1_idx] := BytesOrder1;
        SendByteArray[BytesOrder2_idx] := BytesOrder2;
        SendByteArray[BytesOrder3_idx] := BytesOrder3;
        SendByteArray[BytesOrder4_idx] := BytesOrder4;
    INT#3412:
        SendByteArray[BytesOrder1_idx] := BytesOrder3;
        SendByteArray[BytesOrder2_idx] := BytesOrder4;
        SendByteArray[BytesOrder3_idx] := BytesOrder1;
        SendByteArray[BytesOrder4_idx] := BytesOrder2;
    INT#2143:
        SendByteArray[BytesOrder1_idx] := BytesOrder2;
        SendByteArray[BytesOrder2_idx] := BytesOrder1;
        SendByteArray[BytesOrder3_idx] := BytesOrder4;
        SendByteArray[BytesOrder4_idx] := BytesOrder3;
    INT#4321:
        SendByteArray[BytesOrder1_idx] := BytesOrder4;
        SendByteArray[BytesOrder2_idx] := BytesOrder3;
        SendByteArray[BytesOrder3_idx] := BytesOrder2;
        SendByteArray[BytesOrder4_idx] := BytesOrder1;
END_CASE;

扩展阅读

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.