0

I am trying to read hex values from a Siemens PLC S7-1500 series. I use the S7NetPlus library. I read the database values as bytes and try to print them to the console to check if the data I receive is the same as the PLC has. Since PLCs uses some different datatypes than C# uses there is a little puzzle involved. The following snippet is my attempt to read the PLC data:

var wordS = sp.ReadBytes(DataType.DataBlock, 2, 2, 2);
string test1 = Encoding.BigEndianUnicode.GetString(wordS);
Console.WriteLine($"Word: {test1}");
var dWordS = sp.ReadBytes(DataType.DataBlock, 2, 4, 4);
string test2 = Encoding.UTF8.GetString(dWordS);
Console.WriteLine($"DWord: {test2}");

Database in the PLC

I read the following result in the console when I run the program: Console write result

The hex values are converted to ASCII characters if I am correct.

My question is:

  1. How can I read the word and Dword datatype and print them as a string with the hex value intact.
Nordin
  • 11
  • 1
  • It prolly use own binary protocol and you have to parse it... If you wana print hex values then it's pretty simple as ou are getting bytes array and there are plenty similar questions – Selvin Jan 16 '23 at 10:37
  • Use `Convert.ToHexString` if you're on .NET 5+ or `BitConverter.ToString` if you're not to convert a byte array to a hexadecimal string as described [here](https://stackoverflow.com/a/311179/9363973) – MindSwipe Jan 16 '23 at 10:38
  • @MindSwipe Thanks for the reply, this worked. I will add it as the answer. I could not find that post. I think part of it is that I could not phrase the question in a single question. – Nordin Jan 16 '23 at 11:04
  • Instead of adding a answer here, I'd prefer closing this as a duplicate of that question – MindSwipe Jan 16 '23 at 11:09

1 Answers1

0
    // Word type
    var wordS = sp.ReadBytes(DataType.DataBlock, 2, 2, 2);
    Console.WriteLine($"Word: 16#{ByteArrayToString(wordS)}");

    // DWord type
    var dWordS = sp.ReadBytes(DataType.DataBlock, 2, 4, 4);
    Console.WriteLine($"DWord: 16#{ByteArrayToString(dWordS)}");

Solved the problem for me although I am not reading the 16# but adding that is no problem, since I receive the correct value that is behind it.

Nordin
  • 11
  • 1