round_up() 计算8字节对齐后的大小

round_up.cpp内容如下:

#include <iostream>
using namespace std;

const int kAlign = 8; // kAlign show be powers of 2, say 2, 4 ,8, 16, 32, ...
const int kAlign16 = 16;

int round_up(unsigned int nBytes) { return ((nBytes)+(kAlign - 1)) & ~(kAlign - 1); }
int round_up16(unsigned int nBytes) { return ((nBytes)+(kAlign16 - 1)) & ~(kAlign16 - 1); }

int main(int argc, char **argv)
{
    for (int i = 0; i < 20; ++i)
        cout << i << " round up to " << round_up(i) << endl;
    for (int i = 0; i < 20; ++i)
        cout << i << " round up to (with alignment 16): " << round_up16(i) << endl;
	
    return 0;
}

运行结果如下图所示:

posted @ 2020-07-28 11:24  jackie_astro  阅读(223)  评论(0编辑  收藏  举报