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

看板C_Sharp (C#)作者 (sec2)時間1年前 (2022/07/27 15:00), 1年前編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串5/5 (看更多)
※ 引述《popo14777 (草草)》之銘言: : 標題: Re: [問題] short整數資料overflow解決方式 : 時間: Tue Jul 26 22:04:13 2022 : : ※ 引述《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) : 以上實驗皆有符合我最終需求,程式的部分還不太能理解,程式碼如下: : 其實就是計數器用的暫存器大小有 4-byte 但因為某些緣故其位址被切成 D300 和 D301 各 2-byte 沒辦法一次讀進來 所以要把分兩次讀進來的 D300 和 D301 還原成 int 然後下面的 Function 其實可以簡化成 return ((SourceA & 0xffff) << 16) | (SourceB & 0xffff); 就結束了 基本概念就是 SourceA * 65536 + SourceB 只是因為 API 回傳 short (但內容應該當成 ushort) 所以必須使用位元運算處理成更大的型別再加總 上面的寫法就是純粹使用位元移位完成 如果使用我前一篇的寫法將得到的 a 和 b 都先 cast 成 int 的話 之後 a * 65536 + b 也可以得到一樣的答案 如果對 bitwise operation 不熟悉的話建議可以閱讀 https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators https://bit.ly/3zhHl9M 位元與移位運算子 (C# 參考) ==== 補充 剛剛與朋友討論感覺原 PO 可能連整數型別的數值範圍都不是很能掌握 建議也閱讀 https://docs.microsoft.com/zh-tw/dotnet/csharp/language-reference/builtin-types/integral-numeric-types https://bit.ly/3vinS7C C# 參考 (整數型別) : 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(); : } : : 謝謝 : : -- : ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.161.143.100 (臺灣) : ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1658844255.A.AD0.html -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.110.213.245 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1658905223.A.10A.html ※ 編輯: sec2 (140.110.213.245 臺灣), 07/27/2022 15:14:01

08/10 11:27, 1年前 , 1F
原來是這樣!謝謝
08/10 11:27, 1F
文章代碼(AID): #1YuEA74A (C_Sharp)
文章代碼(AID): #1YuEA74A (C_Sharp)