※ 引述《sec2 (sec2)》之铭言:
: short a = -1;
: var b = BitConverter.GetBytes(a);
: var c = BitConverter.ToUInt16(b);
: c 应该就是你要的了 (=65535)
分享找到的答案:
PLC资料暂存器有高低位,如果存到D300,D300为低位,D301为高位
例1:D300读出-32767(16bit),D301读出0(16bit),计算后为32769(32bit)
例2:D300读出2(16bit),D301读出1(16bit),计算后为65538(32bit)
例3:D300读出3392(16bit),D301读出3(16bit),计算后为200000(32bit)
例4:D300读出-7328(16bit),D301读出22(16bit),计算后为1500000(32bit)
以上实验皆有符合我最终需求,程式的部分还不太能理解,程式码如下:
private static int toInt32(short SourceA, short SourceB)
{
int DataInt32 = 0;
//short SourceA=,SourceB;//A代表低位,B代表高位
DataInt32 |= (SourceB & 0x0000ffff); //不太能理解
DataInt32 = (DataInt32 << 16) | (SourceA & 0x0000ffff); //不太能理解
return DataInt32;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
textPLC.ReadDeviceRandom2("D300", 1, out Readwordbcd);
short a = Readwordbcd;
textPLC.ReadDeviceRandom2("D301", 1, out Readwordbcd);
short b = Readwordbcd;
int D300 = toInt32(a, b);
textBox1.Text = D300.ToString();
}
谢谢