繁体   English   中英

异或后将int转换为字节

[英]Casting int to byte after xoring

我在将大于255的int转换为字节时遇到问题。 问题是我有两个程序执行相同的代码。 一方面,即使编译设置相同,我也有例外;另一方面,我没有。 代码是这样的:

   private static byte[] MixRound(byte[] input, Random RNG, int seed)
    {
        bool[] cellMap = new bool[input.Length];
        byte[] output = new byte[input.Length];
        for (int i = 0; i < input.Length; i++)
        {
            int value = input[NewLocation(cellMap, RNG)];
            int xor = seed * (i + seed);
            int xorValue = value ^ xor;
            output[i] = (byte)(xorValue);
        }
        return output;
    }

引发异常的行是这样的:

 output[i] = (byte)(xorValue);

带有“ System.OverflowException”,表示“算术运算导致溢出”。

我认为在同一台计算机上使用相同代码的两个不同项目是不正常的。

您可以使用checkedunchecked关键字来控制整数溢出:

  // Throw exception
  checked {
    output[i] = (byte)(xorValue);
  }

  // Do not throw exception
  unchecked {
    output[i] = (byte)(xorValue);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM