【问题标题】:C# - Random bytes to bool[] ... and back doesn't work?C# - 随机字节到 bool[] ... 并返回不起作用?
【发布时间】:2017-11-22 07:35:29
【问题描述】:

只是关于旧问题的一些背景...
所以,经过一些测试和几十个断点......我的代码被破坏了。 但是,我已经把它四舍五入到这个函数的某个地方:

        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 
            }
        }

但是修好了!感谢您为我指明正确的方向!

*顺便说一句,错误是我颠倒列表时发生的。

【问题讨论】:

  • 如果您知道问题出在哪里(第 123 行 numToBin(object n) 方法),那么只需简化您的问题并通过仅放置失败的代码以及有关预期结果的更多详细信息来使其更清晰.我在看你的方法,我不明白你在做什么。
  • 好的,稍后我会添加评论。
  • 与其将所有方法调用嵌套在一行中,不如将它们分成单独的行可能更容易,这样您就可以检查方法的返回值。
  • 这里似乎没有问题。

标签: c# algorithm binary


【解决方案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 
        }
    }

是正确版本的代码。

【讨论】:

  • 这里似乎没有答案。
猜你喜欢
  • 2017-02-22
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 2015-01-03
  • 2011-07-28
相关资源
最近更新 更多