Skip to content

Latest commit

 

History

History
90 lines (72 loc) · 1.67 KB

大小端判断与转换.md

File metadata and controls

90 lines (72 loc) · 1.67 KB

大小端判断与转换

大小端判断

OSHostByteOrder 函数

该函数适用于 macOS 10.0+ 或 iOS 系统

int32_t byteOrder = OSHostByteOrder();
switch (byteOrder) {
    case OSLittleEndian: {
        printf("OSLittleEndian\n");
    }
        break;
    case OSBigEndian: {
        printf("OSBigEndian\n");
    }
        break;
    case OSUnknownByteOrder: {
        printf("OSUnknownByteOrder\n");
    }
        break;
}

自定义函数

enum OSEndianType {
    OSEndianTypeUnknown,
    OSEndianTypeLittle,
    OSEndianTypeBig,
};

// 函数原型
enum OSEndianType OSEndianTypeChecker(void);


// 函数定义
enum OSEndianType OSEndianTypeChecker(void) {
    uint16_t num = 0x1234;
    unsigned char *bytePointer = (unsigned char *)#

    bool isBigEndian = bytePointer[0] == 0x12 && bytePointer[1] == 0x34;
    bool isLittleEndian = bytePointer[0] == 0x34 && bytePointer[1] == 0x12;

    if (isBigEndian && !isLittleEndian) {
        return OSEndianTypeBig;
    } else if (!isBigEndian && isLittleEndian) {
        return OSEndianTypeLittle;
    } else {
        return OSEndianTypeUnknown;
    }
}

大小端转换

内置函数族

NTOHL(x)
NTOHS(x)
NTOHLL(x)
HTONL(x)
HTONS(x)
HTONLL(x)

// 以下函数族中的NN为16、32或64
OSSwapIntNN(x)

// 以下函数族中的NN为16、32或64
OSSwapBigToHostConstIntNN(x)
OSSwapBigToHostInt(x)
OSSwapBigToHostIntNN(x)
OSSwapConstIntNN(x)
OSSwapHostToBigConstIntNN(x)
OSSwapHostToBigInt(x)
OSSwapHostToBigIntNN(x)
OSSwapHostToLittleConstIntNN(x)
OSSwapHostToLittleInt(x)
OSSwapHostToLittleIntNN(x)
OSSwapIntNN(x)
OSSwapLittleToHostConstIntNN(x)
OSSwapLittleToHostInt(x)
OSSwapLittleToHostIntNN(x)