C# - 随机字节到bool [] ......然后回来不起作用?

时间:2017-06-19 23:37:47

标签: c# algorithm binary

关于旧问题的一些背景...... Old version of the question
所以,经过一些测试和几十个断点......我的代码被打破了。 但是,我把它简化为这个函数的某个地方:

        public BigInteger getNum()
        {
            BigInteger rtrnVal = 0;
            int pow = 0;
            foreach (bool b in _arr)
            {
                rtrnVal += (b ? BigInteger.Pow(2, pow) : 0);
                pow++;
            }
            return rtrnVal;
        }

这一个......

        public numToBin(object n)
        {
            assignType(n); //Check if the type is valid
            BigInteger r = new BigInteger(Convert.ToInt32(n)); //Make sure that the type is valid
            _arr = new List<bool>(); //Refresh the internal array of booleans
            while (r != 0) //While we arent left with 0...
            {
                //if (!first) if (_arr.Last()) r += 1; //If the last one was true, then add one, because we want the ceiling (round up not down)
                _arr.Add(!r.IsEven); //Add to the list
                r = r / 2; //Divide by two... I think this may potentially be 
            }
        }

但修好了!谢谢你指出我正确的方向!

* BTW错误是我颠倒了这个清单。

1 个答案:

答案 0 :(得分:-1)

    public BigInteger getNum()
    {
        BigInteger rtrnVal = 0;
        int pow = 0;
        foreach (bool b in _arr)
        {
            rtrnVal += (b ? BigInteger.Pow(2, pow) : 0);
            pow++;
        }
        return rtrnVal;
    }

这一个......

    public numToBin(object n)
    {
        assignType(n); //Check if the type is valid
        BigInteger r = new BigInteger(Convert.ToInt32(n)); //Make sure that the type is valid
        _arr = new List<bool>(); //Refresh the internal array of booleans
        while (r != 0) //While we arent left with 0...
        {
            //if (!first) if (_arr.Last()) r += 1; //If the last one was true, then add one, because we want the ceiling (round up not down)
            _arr.Add(!r.IsEven); //Add to the list
            r = r / 2; //Divide by two... I think this may potentially be 
        }
    }

代码的正确版本。