整数转换为Bn

时间:2016-06-15 15:39:43

标签: c#

我有一段我无法理解的c#代码。在IntToBin循环的第一次迭代期间,我理解移位运算符将其转换为字节值7,但在第二次传递时,字节值为224.如何实现224。

   static void Main(string[] args)
    {
        IntToBin(2016,2);
        //Console.Write((byte)2016);
    }

    public static byte[] IntToBin(int from, int len)
    {
        byte[] to = new byte[len];
        int max = len;
        int t;
        for (int i_move = max - 1, i_to = 0; i_move >= 0; i_move--, i_to++)
        {

            to[i_to] = (byte)(from >> (8 * i_move));
        }

        return to;
    }

1 个答案:

答案 0 :(得分:1)

据我所知,你对这一行有困难

to[i_to] = (byte)(from >> (8 * i_move));

您可以轻松测试

2016 == 7 * 256 + 224

现在如何获得这些数字?

Shift运算符>>实际上是一个整数除法 两个权力:

  >> 0 - no division (division by 1) 
  >> 1 - division by 2
  >> 2 - division by 4
  ...
  >> 8 * i_move - dision by 2**(8*i_move) i.e. division by 256 ** i_move

(byte)强制转换实际上是余下运算符% 256 因为(byte)返回最后一个字节

现在让我们尝试解开循环

  i_move == 1 // max - 1 where max = 2
  to[0] = (from / 256) % 256;  // = 7

  i_move == 0 
  to[1] = (from / 1) % 256;   //  = 224

一般情况下

  to[0]       = from / (256 ** (len - 1)) % 256;
  to[1]       = from / (256 ** (len - 2)) % 256;
  ...
  to[len - 3] = from / (256 ** 2) % 256;
  to[len - 2] = from / (256) % 256;
  to[len - 1] = from / (1) % 256;