S7NetPlus / s7netplus

S7.NET+ -- A .NET library to connect to Siemens Step7 devices
MIT License
1.34k stars 589 forks source link

S7-300 vb.net DINT negative conversion #366

Closed djp4nd4 closed 3 years ago

djp4nd4 commented 3 years ago

Hi, I'm trying to read a negative DINT 32bit from a DB, following documentation. Documentation for C# says: Read S7 Dint, you need to use ConvertToInt(): int result2 = ((uint)plc.Read("DB1.DBD60")).ConvertToInt();

In vb.net if I use: quota = Convert.ToInt32(plc.Read("DB32.DBD6")) i receive error "Value was either too large or too small for an Int32"

If I use convert.ToInt64 i receive error "arithmetic overflow" quota = Convert.ToInt64(plc.Read("DB32.DBD6"))

If I not use any conversion i receive quota = plc.Read("DB32.DBD6") i receive "quota= 4294967196"

mycroes commented 3 years ago

Hi @djp4nd4,

Documentation for C# says: Read S7 Dint, you need to use ConvertToInt(): int result2 = ((uint)plc.Read("DB1.DBD60")).ConvertToInt();

This should work, even though the implementation of the method isn't great (and that's an understatement).

In vb.net if I use: quota = Convert.ToInt32(plc.Read("DB32.DBD6")) i receive error "Value was either too large or too small for an Int32"

Wait, you read the documentation which tells you to use ConvertToInt(), which is an extension method in S7NetPlus, but instead you're using Convert.ToInt32(), which is a method from .NET Framework itself?

If I use convert.ToInt64 i receive error "arithmetic overflow" quota = Convert.ToInt64(plc.Read("DB32.DBD6"))

I can hardly imagine that, given the number from the last example.

If I not use any conversion i receive quota = plc.Read("DB32.DBD6") i receive "quota= 4294967196"

Tried the following in C# interactive:

> uint x = 4294967196;
> Convert.ToInt32(x)
System.OverflowException: Value was either too large or too small for an Int32.
  + System.Convert.ToInt32(uint)
> Convert.ToInt64(x)
4294967196
> (int)x
-100

Long story short, you want to use quota = (int) plc.Read("DB32.DBD6"). Also, please take note that this is not a S7NetPlus issue (although the right type could've been returned from the Read method in the first place of course), this boils down to the lack of some basic C# skills. Please familiarize yourself with the C# language to avoid opening issues that are not related to S7NetPlus.