将数值上调/下调为2的已知次幂的倍数

作者:追风剑情 发布于:2017-11-14 21:55 分类:Algorithms

示例

using System;

namespace Test4
{
    class Program
    {
        static void Main(string[] args)
        {
            int x1 = 756;
            int x2 = -756;

            for (int i = 3; i <= 10; i++)
            {
                Console.WriteLine("x1={0}, 上调为{1}的倍数={2}, 下调为{1}的倍数={3}", x1, Math.Pow(2, i), CMath.CeilingPow2(x1, i), CMath.FloorPow2(x1, i));
                Console.WriteLine("x2={0}, 上调为{1}的倍数={2}, 下调为{1}的倍数={3}", x2, Math.Pow(2, i), CMath.CeilingPow2(x2, i), CMath.FloorPow2(x2, i));
                Console.WriteLine();
            }

            Console.Read();
        }
    }

    public class CMath
    {
        /// <summary>
        /// 将数值上调为2的已知次幂的倍数
        /// 上调: 向正无穷方向取整
        /// </summary>
        /// <param name="x">输入值</param>
        /// <param name="pow">2的指数</param>
        /// <returns></returns>
        public static int CeilingPow2(int x, int pow)
        {
            //两种写法
            //return (x + (1<<pow)-1) & -(1<<pow);
            return x + (-x & ((1<<pow)-1) );
        }

        /// <summary>
        /// 将数值下调为2的已知次幂的倍数
        /// 下调: 向负无穷方向取整
        /// </summary>
        /// <param name="x">输入值</param>
        /// <param name="pow">2的指数</param>
        /// <returns></returns>
        public static int FloorPow2(int x, int pow)
        {
            //两种写法
            //return (x >> pow) << pow;
            return x & -(1<<pow);
        }
    }
}

运行测试

1111.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号