C语言内存对齐

#include <stdio.h>
#include <stdlib.h>

typedef unsigned char  u_char;

#define NGX_ALIGNMENT   sizeof(unsigned long)    /* platform word */
#define ngx_align(d, a)     (((d) + (a - 1)) & ~(a - 1))  /* Integer multiple alignment */
#define ngx_align_ptr(p, a)                                                   \
    (u_char *) (((uintptr_t) (p) + ((uintptr_t) a - 1)) & ~((uintptr_t) a - 1))     /* Pointers are aligned by integer multiples */

int main(int argc, char *argv[])
{
#ifndef __cplusplus
    u_char* ch = (u_char *)0x00000065;
#else
    u_char* ch = reinterpret_cast<u_char*>(0x00000065);
#endif

    u_char* c = reinterpret_cast<u_char*>(0x00000068 & 0xFFFFFFFC);

    //printf("((uintptr_t)(ch)+((uintptr_t)NGX_ALIGNMENT - 1)): 0x%p\n", ((uintptr_t)(ch)+((uintptr_t)NGX_ALIGNMENT - 1)));
    //printf("~((uintptr_t) a - 1): 0x%p\n", ~((uintptr_t)NGX_ALIGNMENT - 1));
    //printf("(0x00000068 & 0xFFFFFFFC) c: 0x%p\n", c);
    printf("The alignment multiple is %u.\n", NGX_ALIGNMENT);
    printf("Before memory alignment ch: 0x%p.\n", ch);

    ch = ngx_align_ptr(ch, NGX_ALIGNMENT);
    printf("After memory alignment ch: 0x%p.\n", ch);

    return 0;
}

更新中。。。

上一篇:通过lua将nginx请求状态码转变为自定义状态码


下一篇:nginx的一些优化