gpt4 book ai didi

c# - 整数到 Bn 的转换

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:26 26 4
gpt4 key购买 nike

我有一段我无法理解的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;
}

最佳答案

据我所知,你对这条线有困难

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

你可以很容易地测试它

2016 == 7 * 256 + 224

现在如何得到这些数字?

移位运算符 >>> 实际上是一个整数除法2 的幂:

  >> 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) cast 实际上是 remainder operator % 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;

关于c# - 整数到 Bn 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37839951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com