gpt4 book ai didi

c# - 奇怪的 SNMP 移位操作

转载 作者:行者123 更新时间:2023-11-30 16:17:22 25 4
gpt4 key购买 nike

以下摘自 Richard Blum 的《C# Network Programmingm》一书:

public byte[] get(string request, string host, string community, string_ mibstring)
{
byte[] packet = new byte[1024];
byte[] mib = new byte[1024];
int snmplen;
int comlen = community.Length;
string[] mibvals = mibstring.Split('.');
int miblen = mibvals.Length;
int cnt = 0, temp, i;
int orgmiblen = miblen;
int pos = 0;
// Convert the string MIB into a byte array of integer values
// Unfortunately, values over 128 require multiple bytes
// which also increases the MIB length
for (i = 0; i < orgmiblen; i++)
{
temp = Convert.ToInt16(mibvals[i]);
if (temp > 127)
{
mib[cnt] = Convert.ToByte(128 + (temp / 128));
mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
cnt += 2;
miblen++;
}
else
{
mib[cnt] = Convert.ToByte(temp);
cnt++;
}
}
snmplen = 29 + comlen + miblen - 1; //Length of entire SNMP packet
//The SNMP sequence start
packet[pos++] = 0x30; //Sequence start
packet[pos++] = Convert.ToByte(snmplen - 2); //sequence size
//SNMP version
packet[pos++] = 0x02; //Integer type
packet[pos++] = 0x01; //length
packet[pos++] = 0x00; //SNMP version 1
//Community name
packet[pos++] = 0x04; // String type
packet[pos++] = Convert.ToByte(comlen); //length
//Convert community name to byte array
byte[] data = Encoding.ASCII.GetBytes(community);
for (i = 0; i < data.Length; i++)
{
packet[pos++] = data[i];
}
}

我没看懂下面的代码:

    for (i = 0; i < orgmiblen; i++)
{
temp = Convert.ToInt16(mibvals[i]);
if (temp > 127)
{
mib[cnt] = Convert.ToByte(128 + (temp / 128));
mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
cnt += 2;
miblen++;
}
else
{
mib[cnt] = Convert.ToByte(temp);
cnt++;
}
}

我知道这是为了在温度大于一个字节的情况下放入两个字节。但是128+(temp/128)然后是第二个字节:temp-(temp/128)*128,这是我不明白的计算是什么。

请帮忙,谢谢。

最佳答案

如果 temp 大于 127,那么它将被分成 2 个字节。让我们看两个例子/

temp = 100;
128 + (temp / 128); //(temp / 128) = 0 + 128 so the mib[cnt] is set to 128
temp - ((temp/128) * 128); // 0*128 = 0. subtracted from temp leaves the original. so you end up with

mib[cnt] = 128;
mib[cnt+1] = 100;

现在如果温度 > 127

temp = 200;
128 + (temp / 128); //(temp / 128) = 1 + 128 so the mib[cnt] is set to 129
temp - ((temp/128) * 128); // 1*128 = 128. 200-128 = 72. so you end up with

mib[cnt] = 129;
mib[cnt+1] = 72;

所以基本上,它采用一个数字,测试它是否 > 7 个字节(-128 => +127 是一个带符号的字节),如果您提供的数字会溢出该范围,它会将其转换为 2 个字节的值/

关于c# - 奇怪的 SNMP 移位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17270451/

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