chrome的base库中求最接近n的2的多少次幂,也就是k=log2(n); 求k的算法

本文介绍了一个实用的位操作工具库,其中包括两个核心函数:Log2Floor和Log2Ceiling。Log2Floor函数返回不大于输入整数的最大2的幂次方的指数,而Log2Ceiling则返回不小于输入整数的最小2的幂次方的指数。

// 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_

评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值