iOS 内存字节对齐

记录下苹果实现内存字节对齐的代码以下:bash

#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
#endif

static inline uint32_t word_align(uint32_t x) {
    return (x + WORD_MASK) & ~WORD_MASK;
}
复制代码

对比记录不一样方案:ui

func word_align(x: UInt32) -> UInt32 {
//        return (x + 7) / 8 * 8      //方案1,相对位运算效率要低
//        return ((x + 7) >> 3) << 3  //方案2,经过右移左移,低三位清0
        return (x + 7) & (~7)         //苹果方案,另外一种低三位清0方式
    }
复制代码
相关文章
相关标签/搜索