记录下苹果实现内存字节对齐的代码如下:
#ifdef __LP64__# define WORD_SHIFT 3UL# define WORD_MASK 7UL# define WORD_BITS 64#else# define WORD_SHIFT 2UL# define WORD_MASK 3UL# define WORD_BITS 32#endifstatic inline uint32_t word_align(uint32_t x) { return (x + WORD_MASK) & ~WORD_MASK;}复制代码
对比记录不同方案:
func word_align(x: UInt32) -> UInt32 {// return (x + 7) / 8 * 8 //方案1,相对位运算效率要低// return ((x + 7) >> 3) << 3 //方案2,通过右移左移,低三位清0 return (x + 7) & (~7) //苹果方案,另一种低三位清0方式 }复制代码