位序与字节序

内容纲要

一、位序

1、判断位序

1.1、代码判断

判断位序的方式。可通过代码测试得出。

typedef struct {
    uint8_t  bit0:1;
    uint8_t  bit1:1:
} bit_test_t;
bit_test_t bit_test;
bit_test.bit0 = 1;
print("Bit order = %d", bit_test);

1.2、宏判断

在linux系统中存在一个宏,标识着系统的位序。

#include <asm/byteorder.h>
#ifdef __LITTLE_ENDIAN_BITFIELD
    print("little bit order\n");
#endif
#ifdef __BIG_ENDIAN_BITFIELD
    print("big bit order\n");
#endif

2、小端模式:

按位,自右向左依次将1 0 1 0 1 1 0 1存放在0地址单元中的第0位到第7位, 如下图:

图1-1

3、大端模式:

按位,自左向右依次将1 0 1 1 0 1 0 1存放在0地址单元中的第0位到第7位, 如下图:

图1-2

二、字节序

1、判断字节序

1.1、代码判断

1.2、宏判断

在linux系统中有个宏,标识了字节序。

#include <endian.h>
#if __BYTE_ORDER == __BID_ENDIAN
    print("Byte order big-endian");
#endif
#if __BYTE_ORDER == __LITTLE_ENDIAN
    print("Byte order little-endian");
#endif

2、小端模式:

按字节, 自右向左依次将78 56 34 12这四个字节存放在自0地址开始的4个内存单元(每个单元存放一个字节)中, 如下图:

图2-1

3、大端模式:

按字节, 自左向右依次将12 34 56 78这四个字节存放在自0地址开始的4个内存单元(每个单元存放一个字节)中,如下图:

图2-2

留下评论