// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file defines some bit utilities.
#ifndef BASE_BITS_H_
#define BASE_BITS_H_
#include "base/basictypes.h"
#include "base/logging.h"
namespace base
{
namespace bits
{
// Returns the integer i such as 2^i <= n < 2^(i+1)
inline int Log2Floor(uint32 n)
{
if (n == 0)
return -1;
int log = 0;
uint32 value = n;
for (int i = 4; i >= 0; --i)
{
int shift = (1 << i);
uint32 x = value >> shift;
if (x != 0)
{
value = x;
log += shift;
}
}
DCHECK_EQ(value, 1u);
return log;
}
// Returns the integer i such as 2^(i-1) < n <= 2^i
inline int Log2Ceiling(uint32 n)
{
if (n == 0)
{
return -1;
}
else
{
// Log2Floor returns -1 for 0, so the following works correctly for n=1.
return 1 + Log2Floor(n - 1);
}
}
} // namespace bits
} // namespace base
#endif // BASE_BITS_H_
本文介绍了一个实用的位操作工具库,其中包括两个核心函数:Log2Floor和Log2Ceiling。Log2Floor函数返回不大于输入整数的最大2的幂次方的指数,而Log2Ceiling则返回不小于输入整数的最小2的幂次方的指数。
1万+

被折叠的 条评论
为什么被折叠?



