Re: [問題] short整數資料overflow解決方式

作者: popo14777 (草草)   2022-07-26 22:04:13
※ 引述《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();
}
謝謝

Links booklink

Contact Us: admin [ a t ] ucptt.com