将指定数值解析出1,2,4,8,16 等数组

     /// <summary>
        /// 从数值中解析出底数等于2的多个指数幂值集合
        /// 例如:input=15,将解析出[1,2,4,8],即表示15包含2o,21,22,23
        /// </summary>
        /// <param name="input">数值</param>
        /// <returns></returns>
        public static List<int> Exponent(int input)
        {
            List<int> result = new List<int>();

            //将数值以二进制形式字符串表示
            string str = Convert.ToString(input, 2);

            int index = str.Length - 1;

            while(index >= 0)
            {
                if(str[index] == '1')
                {

                    int val = (int)Math.Pow(2, str.Length - index - 1);

                    result.Add(val);
                }

                index--;
            }

            return result;
        }

 

posted @ 2017-11-06 11:48  kunjust  阅读(181)  评论(0)    收藏  举报