宏实现大小端转换

宏实现大小端转换


/*  定义多行宏时在每一行后面加 '\' */
#define sw16(x) \
    ((short)( \
        (((short)(x) & (short)0x00ffU) << 8 ) | \
        (((short)(x) & (short)0xff00U) >> 8 ) ))

 

假设x=0xaabb
(short)(x) & (short)0x00ffU) 与将16位数高8位置0   成了0x00bb

然后<<8 向左移8位后 低8位变成了高8位 低8位补0  结果为0xbb00


(((short)(x) & (short)0xff00U) >> 8 ) )) 恰好相反 得到的结果为0x00aa


两个结果再 或一下 0xbb00 | 0x00aa就成了0xbbaa

 

宏实现大小端和转网络字节序

 

typedef unsigned short int uint16;
typedef unsigned long int uint32;
 
 
#define BigLittleSwap16(A)        ((((uint16)(A) & 0xff00) >> 8) | \
                                                       (((uint16)(A) & 0x00ff) << 8))
 
 
#define BigLittleSwap32(A)        ((((uint32)(A) & 0xff000000) >> 24) | \
                                                       (((uint32)(A) & 0x00ff0000) >> 8) | \
                                                       (((uint32)(A) & 0x0000ff00) << 8) | \
                                                       (((uint32)(A) & 0x000000ff) << 24))

 

你可能感兴趣的:(疑难算法,C语言)