C 语言常用方法技巧

2020-01-06 16:52:50王旭

得到一个字节的低位和高位


typedef unsigned char byte; /* Unsigned 8 bit value type */
typedef unsigned short word; /* Unsigned 16 bit value type */

#define WORD_L(var) ((byte)(word)(var)&(0xFF))
#define WORD_H(var) ((byte)(word)(var)>>(8))

返回一个比 X 大的接近 8 的倍数

#define RND8(x) ((((x) + 7) >> 3) << 3)

防止溢出的方法


#define INC_SAT(val)
 ((val) = ( ((val) + 1) > (val)) ? ((val) + 1):(val) )

返回数组元素的个数


#define ARR_SIZE(a)
 ( (sizeof(a)) / (sizeof(a[0])) )

返回一个无符号数的后 n 位数


typedef unsigned long dword; /* Unsigned 32 bit value type */ 

#define MOD_BY_POWER_OF_TWO(val, mod_by)
 ((dword)(val)&(dword)(2<<(mod_by) - 1))

IO 空间映射在存储空间中的结构


typedef unsigned char byte; /* Unsigned 8 bit value type */
typedef unsigned short word; /* Unsigned 16 bit value type */
typedef unsigned long dword; /* Unsigned 32 bit value type */

#define outp(port)  (*((volatile byte *)(port)))
#define outpw(port)  (*((volatile word *)(port)))
#define outpdw(port) (*((volatile dword *)(port)))

#define inp(port, val)  (*((volatile byte *)(port))) = (byte)(val)
#define inpw(port, val)  (*((volatile word *)(port))) = (word)(val)
#define inpdw(port, val) (*((volatile dword *)(port))) = (dword)(val)

宏中 "#" 和 "##" 的用法

一、使用 "#" 把宏参数变为一个字符串, 用 "##" 把两个宏参数贴合在一起。


 #define STR(val) (#val)
 #define CONS(a, b) (int)(a#