Re: [问题] short整数资料overflow解决方式

楼主: sec2 (sec2)   2022-07-27 15:00:20
※ 引述《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();
: }
:
: 谢谢
:
:
作者: popo14777 (草草)   2022-08-10 11:27:00
原来是这样!谢谢

Links booklink

Contact Us: admin [ a t ] ucptt.com