这是我创建的表单,它将从plc获取的所有数据显示为十六进制格式,现在我想使用该转换按钮将其转换为真实世界格式。
转换按钮不会转换值,只是打印相同的十六进制输出。我还提到了转换按钮代码。
Readbtn点击从plc读取数据
private void ReadBtn_Click(object sender, EventArgs e) {
GetSelectedDB();
}
GetSelectedDB方法
void GetSelectedDB() {
int Size = 65536; // 64 K (the maximum for a S7400)
byte[] Buffer = new byte[Size];
txtDBGet.Text = "";
int Result = Client.DBGet(System.Convert.ToInt32(TxtDB.Text),Buffer, ref Size);
ShowResult(Result);
if (Result == 0) {
HexDump(txtDBGet, Buffer, Size);
}
}
这是将输出打印到文本框
的Hexdump代码private void HexDump(TextBox DumpBox, byte[] bytes, int Size) {
if (bytes == null)
return;
int bytesLength = Size;
int bytesPerLine = 16;
char[] HexChars = "0123456789ABCDEF".ToCharArray();
int firstHexColumn =
8 // 8 characters for the address
+ 3; // 3 spaces
int firstCharColumn = firstHexColumn
+ bytesPerLine * 3 // - 2 digit for the hexadecimal value and 1 space
+ (bytesPerLine - 1) / 8 // - 1 extra space every 8 characters from the 9th
+ 2; // 2 spaces
int lineLength = firstCharColumn
+ bytesPerLine // - characters to show the ascii value
+ Environment.NewLine.Length; // Carriage return and line feed (should normally be 2)
char[] line = (new String(' ', lineLength - 2) + Environment.NewLine).ToCharArray();
int expectedLines = (bytesLength + bytesPerLine - 1) / bytesPerLine;
StringBuilder result = new StringBuilder(expectedLines * lineLength);
for (int i = 0; i < bytesLength; i += bytesPerLine) {
line[0] = HexChars[(i >> 28) & 0xF];
line[1] = HexChars[(i >> 24) & 0xF];
line[2] = HexChars[(i >> 20) & 0xF];
line[3] = HexChars[(i >> 16) & 0xF];
line[4] = HexChars[(i >> 12) & 0xF];
line[5] = HexChars[(i >> 8) & 0xF];
line[6] = HexChars[(i >> 4) & 0xF];
line[7] = HexChars[(i >> 0) & 0xF];
int hexColumn = firstHexColumn;
int charColumn = firstCharColumn;
for (int j = 0; j < bytesPerLine; j++) {
if (j > 0 && (j & 7) == 0)
hexColumn++;
if (i + j >= bytesLength) {
line[hexColumn] = ' ';
line[hexColumn + 1] = ' ';
line[charColumn] = ' ';
} else {
byte b = bytes[i + j];
line[hexColumn] = HexChars[(b >> 4) & 0xF];
line[hexColumn + 1] = HexChars[b & 0xF];
line[charColumn] = (b < 32 ? '·' : (char)b);
}
hexColumn += 3;
charColumn++;
}
result.Append(line);
}
DumpBox.Text = result.ToString();
}
这是我使用的转换按钮,但没有将数据转换为所需的格式,只是向我显示相同的数据
private void Convert_btn_Click(object sender, EventArgs e) {
string hexValue = txtDBGet.Text.ToString();
char[] myarr = hexValue.ToCharArray();
string[] ids = textdbconv.Text.Split(' ');
for (int i = 0; i < myarr.Length; i++) {
textdbconv.AppendText(myarr[i].ToString() + "");
}
}