using Newtonsoft.Json;
using NLog;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls.UI;
namespace BaseFunction
{
//==========================================================================================
//通用功能类
public class NLogger
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public static void Trace(string message)
{ logger.Trace(message); }
public static void Debug(string message)
{ logger.Debug(message); }
public static void Info(string message)
{ logger.Info(message); }
public static void Warn(string message)
{ logger.Warn(message); }
public static void Error(string message)
{ logger.Error(message); }
public static void Fatal(string message)
{ logger.Fatal(message); }
}
public class MyBase
{
public static RadLabelElement rleMessage;
#region 内存回收
[DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
///
/// 释放内存
///
public static void ClearMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
public static void ClearMemory_PCDMIS()
{
Process[] m_Process = Process.GetProcessesByName("PCDLRN");
for (int i = 0; i < m_Process.Length; i++)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(m_Process[i].Handle, -1, -1);
}
}
}
#endregion 内存回收
public static void KillSoftware(string strSoftwareName)
{
Process[] xc = Process.GetProcesses();
try
{
foreach (Process xc1 in xc)
{
if (xc1.ProcessName.ToLower() == strSoftwareName.ToLower())
{
xc1.Kill();
}
}
}
catch (Exception ex)
{
MyBase.TraceWriteLine("Kill " + strSoftwareName + " Failed: " + ex.ToString());
}
}
public static void DeleteAllFiles(string strPath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(strPath);
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo) //判断是否文件夹
{
DirectoryInfo subdir = new DirectoryInfo(i.FullName);
subdir.Delete(true); //删除子目录和文件
}
else
{
File.Delete(i.FullName); //删除指定文件
}
}
MyBase.TraceWriteLine("首次启动软件,遍历删除路径:" + strPath + "下的文件全部删除");
}
catch (Exception e)
{
MyBase.TraceWriteLine("遍历删除路径:" + strPath + "下的文件失败:" + e.ToString());
}
}
#region 界面控件操作
///
/// 根据指定容器和控件名字,获得控件
///
/// 容器
/// 控件名字
/// 控件
public static object GetControlInstance(object obj, string strControlName, Form mainForm)
{
IEnumerator Controls = null;//所有控件
Control c = null;//当前控件
Object cResult = null;//查找结果
if (obj.GetType() == mainForm.GetType())//窗体
{
Controls = mainForm.Controls.GetEnumerator();
}
else//控件
{
Controls = ((Control)obj).Controls.GetEnumerator();
}
while (Controls.MoveNext())//遍历操作
{
c = (Control)Controls.Current;//当前控件
if (c.HasChildren)//当前控件是个容器
{
cResult = GetControlInstance(c, strControlName, mainForm);//递归查找
if (cResult == null)//当前容器中没有,跳出,继续查找
continue;
else//找到控件,返回
return cResult;
}
else if (c.Name == strControlName)//不是容器,同时找到控件,返回
{
return c;
}
}
return null;//控件不存在
}
///
/// 获取主控件上的子控件的名称
///
/// 主控件名称
/// 子控件名称
///
public static object GetChildControl(object obj, string strControlName)
{
Control m_Ctrl = null;//当前控件
IEnumerator Controls = ((Control)obj).Controls.GetEnumerator();
while (Controls.MoveNext())
{
m_Ctrl = (Control)Controls.Current;//当前控件
if (m_Ctrl.Name == strControlName)
{
return m_Ctrl;
}
}
return null;//控件不存在
}
public static void AddDebugText(TextBox tb, string str, int length = 200)
{
try
{
TraceWriteLine(str);
string strTime = DateTime.Now.ToString("HH:mm:ss") + "--";
tb.Text += (strTime + str);
tb.Text += "\r\n";
tb.Select(tb.TextLength, 0);
tb.ScrollToCaret();
if (tb.Lines.Length > length)
{
tb.Clear();
}
}
finally { }
}
///
/// 向RichTextBox控件中添加文本信息
///
/// RichTextBox控件类
/// 要显示的文本信息内容
/// 文本显示的颜色
public static void AddDebugTextToRTB(RichTextBox RTB, string str, Color m_Color = new Color())
{
try
{
TraceWriteLine(str);//将文本信息同步到debug.txt文件中
RTB.BeginInvoke((EventHandler)delegate
{
Color SetColor = Color.Black;
if (m_Color == new Color())
{
if (str.ToUpper().Contains("ERROR") || str.ToUpper().Contains("错误") || str.ToUpper().Contains("出错") || str.ToUpper().Contains("EXCEPTION") || str.ToUpper().Contains("异常") || str.ToUpper().Contains("失败"))
{
SetColor = Color.Red;
}
else if (str.ToUpper().Contains("WARNING") || str.ToUpper().Contains("警告"))
{
SetColor = Color.DarkOrange;
}
}
else
{
SetColor = m_Color;
}
string strText = str + Environment.NewLine; //DateTime.Now.ToString("HH:mm:ss.fff") + "--" +
RTB.SelectionStart = RTB.TextLength;
if (string.IsNullOrEmpty(str))
RichTextUnit.SetText(RTB, " " + Environment.NewLine, SetColor, false, 14);
else
RichTextUnit.SetText(RTB, strText, SetColor, false, 14);
if (RTB.Lines.Length > 2000)
{
RTB.Select(0, RTB.TextLength / 2);
RTB.Cut();
}
RTB.ScrollToCaret();
});
}
catch { }
}
///
/// 写debug文件,记录程序过程
///
/// 要写入日志的内容
public static void TraceWriteLine(string str)
{
try
{
if (rleMessage != null)
{
rleMessage.Text = str;
}
if (str.Contains("警告") || str.ToUpper().Contains("WARN"))
{
NLogger.Warn(str);
}
else if (str.Contains("错误") || str.ToUpper().Contains("ERROR") || str.Contains("失败"))
{
NLogger.Error(str);
}
else
{
NLogger.Info(str);
}
Trace.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "--" + str);
Trace.Unindent();
Trace.Flush();
}
catch { }
}
public static string InputBox(string Caption, string Hint, string DefaultTxt, string btn1 = "OK", string btn2 = "Cancel", char Strstyle = '*', bool bShowData = false)
{
if (Strstyle == '\0')
Strstyle = '*';
Form InputForm = new Form();
InputForm.MinimizeBox = false;
InputForm.MaximizeBox = false;
InputForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
InputForm.StartPosition = FormStartPosition.CenterScreen;
InputForm.Width = 300;
InputForm.Height = 180;
InputForm.Text = Caption;
InputForm.Font = new System.Drawing.Font("Segoe UI", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
Label lbl = new Label();
lbl.Text = Hint;
lbl.Left = 25;
lbl.Top = 20;
lbl.Parent = InputForm;
lbl.AutoSize = true;
TextBox tb = new TextBox();
tb.Left = 30;
tb.Top = 45;
tb.Width = 230;
tb.Parent = InputForm;
tb.Text = DefaultTxt;
if (bShowData == false)
tb.PasswordChar = Strstyle;
tb.SelectAll();
Button btnok = new Button();
btnok.Left = 90;
btnok.Top = 90;
btnok.Height = 30;
btnok.Parent = InputForm;
btnok.Text = btn1;
InputForm.AcceptButton = btnok;//回车响应
btnok.DialogResult = DialogResult.OK;
Button btncancal = new Button();
btncancal.Left = 185;
btncancal.Top = 90;
btncancal.Height = 30;
btncancal.Parent = InputForm;
btncancal.Text = btn2;
btncancal.DialogResult = DialogResult.Cancel;
try
{
if (InputForm.ShowDialog() == DialogResult.OK)
{
return tb.Text;
}
else
{
return "-999.999";
}
}
finally
{
InputForm.Dispose();
}
}
///
/// 操作提示框,0 = 取消; 1 = 第一个按钮; 2 = 第二个按钮
///
/// 错误信息
/// 标题
/// 第一个按钮名字
/// 第二个按钮名字
/// 第三个按钮名字
/// 背景颜色,默认无色,1=红色
///
public static int MessageBox(string strError, string Caption, string btnName1 = "YES", string btnName2 = "NO", string btnName3 = "Cancel", int iColor = 0)
{
Form ErrorForm = new Form();
ErrorForm.MinimizeBox = false;
ErrorForm.MaximizeBox = false;
ErrorForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
ErrorForm.StartPosition = FormStartPosition.CenterScreen;
ErrorForm.Width = 480;
ErrorForm.Height = 300;
ErrorForm.Text = Caption;
ErrorForm.Font = new System.Drawing.Font("宋体", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));
TextBox tb = new TextBox();
tb.Parent = ErrorForm;
tb.Text = strError;
tb.Multiline = true;
tb.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
tb.Location = new System.Drawing.Point(20, 20);
tb.Size = new System.Drawing.Size(440, 170);
tb.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
tb.Font = new Font("宋体", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
if (iColor == 1)
tb.BackColor = Color.Red;
Button btnYes = new Button();
btnYes.Location = new System.Drawing.Point(30, 210);
btnYes.Size = new System.Drawing.Size(100, 40);
btnYes.Parent = ErrorForm;
btnYes.Text = btnName1;
btnYes.DialogResult = DialogResult.Yes;
ErrorForm.AcceptButton = btnYes;//回车响应
Button btnNO = new Button();
btnNO.Location = new System.Drawing.Point(190, 210);
btnNO.Size = new System.Drawing.Size(100, 40);
btnNO.Parent = ErrorForm;
btnNO.Text = btnName2;
btnNO.DialogResult = DialogResult.No;
ErrorForm.AcceptButton = btnNO;//回车响应
Button btncancal = new Button();
btncancal.Location = new System.Drawing.Point(350, 210);
btncancal.Size = new System.Drawing.Size(100, 40);
btncancal.Parent = ErrorForm;
btncancal.Text = btnName3;
btncancal.DialogResult = DialogResult.Cancel;
ErrorForm.AcceptButton = btncancal;//回车响应
try
{
btnYes.Select();
switch (ErrorForm.ShowDialog())
{
case DialogResult.Yes: return 1;
case DialogResult.No: return 2;
default: return 0;
}
}
finally
{
ErrorForm.Dispose();
}
}
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int x, int y);
public static void SetCursorPosXY(int dx, int dy)
{
SetCursorPos(dx, dy);
}
public static void SetCursorPosXY(Point point)
{
System.Windows.Forms.Cursor.Position = point;
}
#endregion 界面控件操作
///
/// CopyFiles 函数
///
/// 源路径文件夹路径
/// 目标文件夹路径
/// 文件夹名称
///
public static int CopyFiles(string strSourceFilePath, string strDesFilePath, string strRemak)
{
try
{
if (!Directory.Exists(strDesFilePath))
{
Directory.CreateDirectory(strDesFilePath);
}
DirectoryInfo sDir = new DirectoryInfo(strSourceFilePath);
FileInfo[] fileArray = sDir.GetFiles();
foreach (FileInfo file in fileArray)
{
file.CopyTo(strDesFilePath + "\\" + file.Name, true);
}
System.Windows.Forms.MessageBox.Show("传输" + strRemak + "文件夹中的所有文件成功! ", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return 1;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("传输" + strRemak + "文件夹中的文件错误!原因: " + ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return 0;
}
}
}
public class HardwareInfoBase
{
///
/// 获取指定驱动器的空间总大小(单位为B) ,只需输入代表驱动器的字母即可
///
public static long GetHardDiskSpace(string str_HardDiskName)
{
long totalSize = new long();
str_HardDiskName = str_HardDiskName + ":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
totalSize = drive.TotalSize;
break;
}
}
return totalSize;
}
///
/// 获取指定驱动器的剩余空间总大小(单位为B) ,只需输入代表驱动器的字母即可
///
public static long GetHardDiskFreeSpace(string str_HardDiskName)
{
long freeSpace = new long();
str_HardDiskName = str_HardDiskName + ":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
freeSpace = drive.TotalFreeSpace;
break;
}
}
return freeSpace;
}
///
/// 获取指定驱动器的剩余空间总大小(单位为K) ,只需输入代表驱动器的字母即可
///
public static long GetHardDiskFreeSpace_K(string str_HardDiskName)
{
return GetHardDiskFreeSpace(str_HardDiskName) / 1024;
}
///
/// 获取指定驱动器的剩余空间总大小(单位为M) ,只需输入代表驱动器的字母即可
///
public static long GetHardDiskFreeSpace_M(string str_HardDiskName)
{
return GetHardDiskFreeSpace_K(str_HardDiskName) / 1024;
}
///
/// 获取指定驱动器的剩余空间总大小(单位为G) ,只需输入代表驱动器的字母即可
///
public static long GetHardDiskFreeSpace_G(string str_HardDiskName)
{
return GetHardDiskFreeSpace_M(str_HardDiskName) / 1024;
}
}
//==================================================================================================FileIni
//Ini 文件操作类
public class FileIni
{
[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
public const int OF_READWRITE = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
//判断文件是否被占用 占用=true 未占用 = false
public static bool isFileOccupied(string path)
{
if (!File.Exists(path))
return true;
IntPtr vHandle = _lopen(path, OF_READWRITE | OF_SHARE_DENY_NONE);
if (vHandle == HFILE_ERROR)
return true;
CloseHandle(vHandle);
return false;
}
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileInt(string section, string key, int def, string filePath);
public static bool isFileExists(string path)
{
if (!(File.Exists(path)))
{
MessageBox.Show("文件:" + path + "不存在", "ini文件不存在");
return false;
}
return true;
}
//=====================//=====================//=====================Write data
#region 写INI参数
///
/// 对ini文件进行写操作
///
/// ini文件路径
/// 配置节
/// 键名
/// 要写入的string字符串
public static void WriteString(string path, string section, string key, string value)
{
// section=配置节,key=键名,value=键值,path=路径
WritePrivateProfileString(section, key, value, path);
}
public static void WriteInt(string path, string section, string key, int value = 0)
{
string strRead = ReadString(path, section, key);
string[] strArr = strRead.Split(new char[] { ';' });
string strNote = ";";
string strWrite;
if (strArr.Length > 1)//保留原有注释
{
for (int i = 1; i < strArr.Length; i++)
strNote += strArr[i];
strWrite = value.ToString() + strNote;
}
else
{
strWrite = value.ToString();
}
WritePrivateProfileString(section, key, strWrite, path);
}
public static void WriteDouble(string path, string section, string key, double value = 0)
{
string strRead = ReadString(path, section, key);
string[] strArr = strRead.Split(new char[] { ';' });
string strNote = ";";
string strWrite;
if (strArr.Length > 1)//保留原有注释
{
for (int i = 1; i < strArr.Length; i++)
strNote += strArr[i];
strWrite = value.ToString() + strNote;
}
else
{
strWrite = value.ToString();
}
WritePrivateProfileString(section, key, strWrite, path);
}
public static void WriteBool(string path, string section, string key, bool value = false)
{
string strValue = (value ? "1" : "0");
string strRead = ReadString(path, section, key);
string[] strArr = strRead.Split(new char[] { ';' });
string strNote = ";";
string strWrite;
if (strArr.Length > 1)//保留原有注释
{
for (int i = 1; i < strArr.Length; i++)
strNote += strArr[i];
strWrite = strValue + strNote;
}
else
{
strWrite = strValue;
}
WritePrivateProfileString(section, key, strWrite, path);
}
#endregion 写INI参数
//=====================//=====================//=====================Read data
#region 读INI参数
///
/// 从ini配置文件中读取字符串
///
/// ini文件路径
/// 配置节名称
/// 键名
/// 要读取的string类型内容
public static string ReadString(string path, string section, string key)
{
// 每次从ini中读取多少字节 // section=配置节,key=键名,temp=上面,path=路径
System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
GetPrivateProfileString(section, key, "", temp, 255, path);
String str = temp.ToString();
string[] strArr = str.Split(new char[] { ';' });
string strRead = "";
if (strArr.Length > 0)
{
strRead = strArr[0];
}
return strRead;
}
///
/// 从ini配置文件中读取Int类型
///
/// ini文件路径
/// 配置节名称
/// 键名
/// 读不到时默认返回值:0
/// 要读取的Int类型数据
public static int ReadInt(string path, string section, string key, int defValue = 0)
{
return GetPrivateProfileInt(section, key, defValue, path);
}
public static double ReadDouble(string path, string section, string key, double defValue = 0)
{
System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
GetPrivateProfileString(section, key, defValue.ToString(), temp, 255, path);
String str = temp.ToString();
string[] strArr = str.Split(new char[] { ';' });
double ReData;
if (strArr.Length > 0)
{
ReData = Convert.ToDouble(strArr[0]);
}
else
{
ReData = defValue;
}
return ReData;
}
public static bool ReadBool(string path, string section, string key, int defValue = 0)
{
int val = GetPrivateProfileInt(section, key, defValue, path);
if (val != 0)
return true;
else
return false;
}
#endregion 读INI参数
}
//==================================================================================================SoundBase
///
/// 声音播放类
///
public class SoundBase
{
//public static WMPLib.WindowsMediaPlayer WMPlayer = new WMPLib.WindowsMediaPlayer();
////方法 1
//public static void OpenWinMediaPlayer(string FileName)
//{
// if (!System.IO.File.Exists(FileName))
// {
// MessageBox.Show("File does not exist!");
// return;
// }
// WMPlayer.URL = FileName;
//}
//public static void OpenWinMediaPlayer(WMPLib.WindowsMediaPlayer WinMediaPlayer, string FileName)
//{
// if (!System.IO.File.Exists(FileName))
// {
// MessageBox.Show("File does not exist!");
// return;
// }
// WinMediaPlayer.URL = FileName;
//}
//public static void OpenWinMediaPlayerDialogFile()
//{
// OpenFileDialog FileDialog = new OpenFileDialog();
// FileDialog.AddExtension = true;
// FileDialog.CheckFileExists = true;
// FileDialog.CheckPathExists = true;
// //the next sentence must be in single line
// FileDialog.Filter = "WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi|所有文件 (*.*)|*.*";
// FileDialog.DefaultExt = "*.mp3";
// if (FileDialog.ShowDialog() == DialogResult.OK)
// {
// WMPlayer.URL = FileDialog.FileName;
// }
//}
//public static void OpenWinMediaPlayerDialogFile(WMPLib.WindowsMediaPlayer WinMediaPlayer)
//{
// OpenFileDialog FileDialog = new OpenFileDialog();
// FileDialog.AddExtension = true;
// FileDialog.CheckFileExists = true;
// FileDialog.CheckPathExists = true;
// //the next sentence must be in single line
// FileDialog.Filter = "WAV文件(*.wav)|*.wav|MP3文件(*.mp3)|*.mp3|VCD文件(*.dat)|*.dat|Audio文件(*.avi)|*.avi|所有文件 (*.*)|*.*";
// FileDialog.DefaultExt = "*.mp3";
// if (FileDialog.ShowDialog() == DialogResult.OK)
// {
// WinMediaPlayer.URL = FileDialog.FileName;
// }
//}
//方法 2
public static void sndPlayerPlay(string FileName)
{
if (!System.IO.File.Exists(FileName))
{
MessageBox.Show("File does not exist!");
return;
}
System.Media.SoundPlayer sndPlayer = new System.Media.SoundPlayer(FileName);
sndPlayer.Load();
sndPlayer.Play();
}
//方法 3
public static void SpVoicePlay(string FileName)
{
//if (!System.IO.File.Exists(FileName))
//{
// MessageBox.Show("File does not exist!");
// return;
//}
//SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
//SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
//spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
//SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
//pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
//spFs.Close();
}
//方法 4 (蜂鸣器--控制台扬声器)
public static void Beep(int frequency, int duration)
{
//振动的Hz频率; //持续的时间,单位“毫秒”。
Console.Beep(frequency, duration);
}
}
//==================================================================================================
///
/// 数据格式化或校验检测
///
internal class FormatCheckBase
{
///
/// 检测是否为十六进制字符串,长度不够在前面添加0
///
/// 输入字符串
/// 长度
/// 输出字符串
/// 检测结果
public static void FormatChecking16(string strInput, int length, out string strOutput, out Boolean Valid)
{
strOutput = "";
Valid = true;
byte temp;
if ((strInput.Length <= length) & (strInput.Length > 0))
{
for (int i = 0; i < strInput.Length; i++)
{
try
{
temp = Convert.ToByte(strInput[i].ToString(), 16);
}
catch
{
Valid = false;
strOutput = "";
break;
}
strOutput += strInput[i];
}
if (Valid & (strInput.Length < length))
{
for (int j = 0; j < length - strInput.Length; j++)
{
strOutput = "0" + strOutput;
}
}
}
else
{
Valid = false;
strOutput = "";
}
}
///
/// 检测是否为十进制字符串,长度不够在前面添加0
///
/// 输入字符串
/// 长度
/// 输出字符串
/// 检测结果
public static bool FormatChecking10(string strInput, int length, out string strOutput)
{
strOutput = "";
byte temp;
try
{
if ((strInput.Length <= length) & (strInput.Length > 0))
{
for (int i = 0; i < strInput.Length; i++)
{
try
{
temp = Convert.ToByte(strInput[i].ToString(), 10);
}
catch
{
strOutput = "";
return false;
}
strOutput += strInput[i];
}
if (strInput.Length < length)
{
for (int j = 0; j < length - strInput.Length; j++)
{
strOutput = "0" + strOutput;
}
}
}
else
{
strOutput = "";
return false;
}
}
catch (Exception ex)
{
MessageBox.Show("格式转换错误:" + ex.Message);
return false;
}
return true;
}
///
/// 每隔n个字符插入一个字符
///
/// 从右边开始插入
/// 源字符串
/// 间隔字符数
/// 待插入值
/// 待补充值,最后不足间隔字符数时,用此字符补齐;Supplement=""时,不补任何字符。
/// 返回新生成字符串
public static string InsertFormat(bool isRight, string input, int interval, string value, string Supplement)
{
if (!isRight)//从左边开始插入
{
for (int i = interval; i < input.Length; i += interval + 1)
{
input = input.Insert(i, value);
}
if (Supplement != "")
{
do
{
if ((input.Length + 1) % (interval + 1) != 0) { input = input + Supplement; }
} while ((input.Length + 1) % (interval + 1) != 0);
}
}
else//从右边开始插入
{
for (int i = input.Length - interval; i > 0; i -= interval)
{
input = input.Insert(i, value);
}
if (Supplement != "")
{
do
{
if ((input.Length + 1) % (interval + 1) != 0) { input = Supplement + input; }
} while ((input.Length + 1) % (interval + 1) != 0);
}
}
return input;
}
///
/// BCC校验,返回校验后的字符串
///
/// 待校验字符串
/// 返回结果
public static string GetBCC(string strCmd)
{
if (strCmd.Length >= 2)
{
byte[] Buffer = Encoding.Default.GetBytes(strCmd);
byte byteBCC = Buffer[0];
for (int i = 1; i < Buffer.Length; i++)
byteBCC ^= Buffer[i];
return Convert.ToChar(byteBCC).ToString();
}
else
{
return null;
}
}
///
/// BCC校验,返回校验后的数组
///
/// 待校验数组
/// 返回结果
public static byte[] GetBCC(byte[] byteData)
{
byte[] byteWrite = new byte[byteData.Length + 1];
if (byteData.Length >= 2)
{
byteData.CopyTo(byteWrite, 0);
byte byteBCC = byteData[0];
for (int i = 1; i < byteData.Length; i++)
byteBCC ^= byteData[i];
byteWrite[byteWrite.Length - 1] = byteBCC;
return byteWrite;
}
else
{
return null;
}
}
///
/// CRC16校验函数
///
public class CRC16Check
{
private const int CRC_LEN = 0;
// Table of CRC values for high-order byte
#region
private static readonly byte[] _auchCRCHi = new byte[]
{
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};
#endregion
// Table of CRC values for low-order byte
#region
private static readonly byte[] _auchCRCLo = new byte[]
{
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};
#endregion
///
/// 计算CRC16校验值 返回一个ushort类型的值,如果要返回Crc高字节和低字节,可重写CalculateCrc16函数为:
///
/// 待校验数组
/// 输出高字节
/// 输出低字节
/// 输出校验值
public static ushort CalculateCrc16(byte[] buffer, out byte crcHi, out byte crcLo)
{
crcHi = 0xff; // high crc byte initialized
crcLo = 0xff; // low crc byte initialized
for (int i = 0; i < buffer.Length - CRC_LEN; i++)
{
int crcIndex = crcHi ^ buffer[i]; // calculate the crc lookup index
crcHi = (byte)(crcLo ^ _auchCRCHi[crcIndex]);
crcLo = _auchCRCLo[crcIndex];
}
return (ushort)(crcHi << 8 | crcLo);
}
}
}
//==================================================================================================ConvertBase
///
/// 数据转换类
///
internal class ConvertBase
{
#region 图像 <--> 数组
///
/// 图像转换为Byte数组
///
public static byte[] ImageToByteArray(Image ImageIn)
{
MemoryStream ms = new MemoryStream();
ImageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
///
/// Byte数组转换为图像
///
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
#endregion
#region 字符串 -> 字节数组
///
/// 十六进制(hexadecimal)字符串转换为字节数组
///
///
///
public static byte[] HexStringToBytes(string str)
{
str = str.Replace(" ", "");
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i += 2)
{
buffer[i / 2] = (byte)Convert.ToByte(str.Substring(i, 2), 16);
}
return buffer;
}
///
/// 十进制(Decimalism)字符串转换为字节数组
///
///
///
public static byte[] DecimalStringToBytes(string str)
{
str = str.Replace(" ", "");
byte[] buffer = new byte[str.Length];
for (int i = 0; i < str.Length; i++)
{
buffer[i] = (byte)Convert.ToByte(str.Substring(i, 1), 10);
}
return buffer;
}
#endregion
#region DataGridView -> DataTable 和 DataSet
public static DataTable GetDataTableFromDataGridView(DataGridView dv)
{
DataTable dt = new DataTable(); DataColumn dc;
for (int i = 0; i < dv.Columns.Count; i++)
{
dc = new DataColumn();
dc.ColumnName = dv.Columns[i].HeaderText.ToString();
dt.Columns.Add(dc);
}
for (int j = 0; j < dv.Rows.Count - 1; j++)
{
DataRow dr = dt.NewRow();
for (int x = 0; x < dv.Columns.Count; x++)
{
dr[x] = dv.Rows[j].Cells[x].Value;
}
dt.Rows.Add(dr);
}
return dt;
}
public static DataSet GetDataSetFromDataGridView(DataGridView ucgrd)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
for (int j = 0; j < ucgrd.Columns.Count; j++)
{ dt.Columns.Add(ucgrd.Columns[j].HeaderCell.Value.ToString()); }
for (int j = 0; j < ucgrd.Rows.Count; j++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < ucgrd.Columns.Count; i++)
{
if (ucgrd.Rows[j].Cells[i].Value != null)
{ dr[i] = ucgrd.Rows[j].Cells[i].Value.ToString(); }
else { dr[i] = ""; }
}
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
return ds;
}
#endregion
#region ListBox.Items, ComboBox.Items -> string[]
public static string[] GetStringsFromListBox(ListBox mListBox)
{
string[] strings = new string[mListBox.Items.Count];
for (int i = 0; i < mListBox.Items.Count; i++)
{
strings[i] = mListBox.Items[i].ToString();
}
return strings;
}
public static string[] GetStringsFromListBox(ComboBox mComboBox)
{
string[] strings = new string[mComboBox.Items.Count];
for (int i = 0; i < mComboBox.Items.Count; i++)
{
strings[i] = mComboBox.Items[i].ToString();
}
return strings;
}
public static void AddStringsToListView(ListView m_ListView, string[] strings)
{
m_ListView.Items.Clear();
for (int i = 0; i < strings.Length; i++)
{
m_ListView.Items.Add(strings[i]);
}
}
#endregion
///
/// 从SYGOLE获取的数据转换函数
///
public class Tool
{
//将十六进制的字符串转化为ushort
public static ushort HexString2Ushort(string s)
{
ushort value = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] != ' ')
{
value = (ushort)(value * 16 + HexStringToHex(s, i));
}
}
return value;
}
//将字节数组形式的mac地址转化为对应的字符串
public static string MacToString(byte[] mac)
{
string MacString = "";
for (int i = 0; i < 6; i++)
{
MacString += ByteToHexString(mac[i]);
if (i < 5)
{
MacString += ":";
}
}
return MacString;
}
//将字符串形式的mac地址转化为对应的字节数组
public static byte[] StringToMac(string str)
{
string temp = "";
for (int i = 0; i < str.Length; i++)
{
if ((str[i] != ' ') && (str[i] != ':'))
{
temp += str[i];
}
}
return HexStringToByte(temp, 0, 6);//6字节长度
}
//判断字符串是否是十六进制字符串
public static bool ValidHexString(string str)
{
for (int i = 0; i < str.Length; i++)
{
if (!
(((str[i] >= '0') && (str[i] <= '9')) ||
((str[i] >= 'a') && (str[i] <= 'f')) ||
((str[i] >= 'A') && (str[i] <= 'F')))
)
{
return false;
}
}
return true;
}
private static string GetStringWithoutSpace(string str, int pos)
{
string temp = "";
for (int i = pos; i < str.Length; i++)
{
if ((str[i] != ' ') && (str[i] != ':'))
{
temp += str[i];
}
}
return temp;
}
//将单个十六进制字符(4 bits)转化为byte
private static byte HexStringToHex(string str, int pos)
{
byte value = 0;
if ((str[pos] >= '0') && (str[pos] <= '9'))
{
value = (byte)(str[pos] - '0');
}
else if ((str[pos] >= 'a') && (str[pos] <= 'f'))
{
value = (byte)(str[pos] - 'a' + 10);
}
else if ((str[pos] >= 'A') && (str[pos] <= 'F'))
{
value = (byte)(str[pos] - 'A' + 10);
}
return value;
}
//将字符串的pos位置开始,转化为数组,转化后数组的长度为cnt
public static byte[] HexStringToByte(string str, int pos, int cnt)
{
if ((!ValidHexString(str)) || ((str.Length - pos) >> 1 < cnt))
{
return null;
}
byte[] data = new byte[cnt];
for (int i = 0; i < cnt; i++)
{
data[i] = (byte)(HexStringToHex(str, 2 * i + pos) * 16 + HexStringToHex(str, 2 * i + pos + 1));
}
return data;
}
public static string bytes2String(byte[] data, int offset, int len)
{
string outString = "";
for (int i = offset; i < len + offset; i++)
{
outString += (char)data[i];
}
return outString;
}
//将字符串的pos位置开始,转化为数组,转化后数组的长度为cnt
public static byte[] HexStringToByte(string str, int pos)
{
string tempStr = GetStringWithoutSpace(str, pos);
return HexStringToByte(tempStr, 0, tempStr.Length >> 1);
}
public static byte HexStringToSingleByte(string str, int pos)
{
byte temp = 0;
int len = 2;
string tempStr = GetStringWithoutSpace(str, pos);
if (tempStr.Length == 0)
{
return 0;
}
else if (tempStr.Length < 2)
{
len = tempStr.Length;
}
else
{
len = 2;
}
for (int i = 0; i < len; i++)
{
temp = (byte)(temp * 16 + HexStringToHex(tempStr, i));
}
return temp;
}
//将字符串的pos位置开始,转化int
public static int HexStringToInt(string s, int pos)
{
string str = "";
int len = (s.Length - pos) > 8 ? 8 : s.Length - pos;
for (int i = pos; i < len; i++)
{
str += s[i];
}
for (int i = len; i < 8; i++)
{
str = "0" + str;
}
if (!ValidHexString(str))
{
return 0;
}
int result = 0;
byte[] data = HexStringToByte(str, 0, 4);
for (int i = 0; i < 4; i++)
{
result = (result << 8) + data[i];
}
return result;
}
//将字节类型的数据转化为十六进制字符串
public static string ByteToHexString(byte data)
{
string outString = "";
if (data < 16)
{
outString += "0";
}
outString += data.ToString("X");
return outString;
}
//将字节类型的数据转化为十六进制字符串
public static string ByteToHexString(byte[] data, int pos, int length, string space)
{
string outString = "";
for (int i = pos; i < pos + length; i++)
{
outString += ByteToHexString(data[i]);
if (i != pos + length - 1)
{
outString += space;
}
}
return outString;
}
//将ushort类型的数据转化为十六进制字符串
public static string ushortToHexString(ushort[] data, int pos, int length)
{
string outString = "";
for (int i = pos; i < pos + length; i++)
{
outString += ByteToHexString((byte)(data[i] >> 8));
outString += ByteToHexString((byte)(data[i] & 0xFF));
}
return outString;
}
}
//==========================================================================================
public class MyConvert
{
//string a = Convert.ToString(5, 2);
//string b = Convert.ToString(11, 8);
//string c = Convert.ToString(11, 16);
//int aa = Convert.ToInt32("101", 2);//二进制转换10进制
//int bb = Convert.ToInt32("13", 8); //八进制转换10进制
//int cc = Convert.ToInt32("b", 16); //十六进制转换10进制
#region C++转换程序(C#里面有完整的转换函数)
//十进制转二制
public static string DtoB(int d)
{
//Console.WriteLine(Convert.ToString(5,2))
string str = "";
//判断该数如果小于2,则直接输出
if (d < 2)
{
str = d.ToString();
}
else
{
int c;
int s = 0;
int n = d;
while (n >= 2)
{
s++;
n = n / 2;
}
int[] m = new int[s];
int i = 0;
do
{
c = d / 2;
m[i++] = d % 2;
d = c;
} while (c >= 2);
str = d.ToString();
for (int j = m.Length - 1; j >= 0; j--)
{
str += m[j].ToString();
}
}
return str;
}
//十进制转八进制
public static string DtoO(int d)
{
string o = "";
if (d < 8)
{
o = d.ToString();
}
else
{
int c;
int s = 0;
int n = d;
int temp = d;
while (n >= 8)
{
s++;
n = n / 8;
}
int[] m = new int[s];
int i = 0;
do
{
c = d / 8;
m[i++] = d % 8;
d = c;
} while (c >= 8);
o = d.ToString();
for (int j = m.Length - 1; j >= 0; j--)
{
o += m[j];
}
}
return o;
}
//十进制转十六进制
public static string DtoX(int d)
{
string x = "";
if (d < 16)
{
x = chang(d);
}
else
{
int c;
int s = 0;
int n = d;
int temp = d;
while (n >= 16)
{
s++;
n = n / 16;
}
string[] m = new string[s];
int i = 0;
do
{
c = d / 16;
m[i++] = chang(d % 16);//判断是否大于10,如果大于10,则转换为A~F的格式
d = c;
} while (c >= 16);
x = chang(d);
for (int j = m.Length - 1; j >= 0; j--)
{
x += m[j];
}
}
return x;
}
//判断是否为10~15之间的数,如果是则进行转换
public static string chang(int d)
{
string x = "";
switch (d)
{
case 10:
x = "A";
break;
case 11:
x = "B";
break;
case 12:
x = "C";
break;
case 13:
x = "D";
break;
case 14:
x = "E";
break;
case 15:
x = "F";
break;
default:
x = d.ToString();
break;
}
return x;
}
public static int XtoD(string instr)
{
int i = Convert.ToInt32("FF", 16); //十六进制转换10进制
int j = Convert.ToInt32("1100", 2);
int k = Convert.ToInt32("12", 8);
return i;
}
#endregion
}
}
//==================================================================================================TcpBase
///
/// 网络通讯通用类函数库
///
internal class TcpBase
{
///
/// 用CMD命令测试网络连接状态
///
/// IP地址或网址
/// Ping结果 连接;超时或其他结果表示未连接
public static string CmdPing(string strIp)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine("ping -n 1 " + strIp);
p.StandardInput.WriteLine("exit");
string strRst = p.StandardOutput.ReadToEnd();
string pingRst = "";
if (strRst.Contains("(0% loss)") || strRst.Contains("(0% 丢失)"))
pingRst = "连接";
else if (strRst.Contains("Request timed out") || strRst.Contains("请求超时"))
pingRst = "超时";
else if (strRst.Contains("Unknown host") || strRst.Contains("无法解析主机"))
pingRst = "无法解析主机";
else if (strRst.Contains("请求找不到主机"))
pingRst = "请求找不到主机";
else if (strRst.Contains("Destination host unreachable."))
pingRst = "无法到达目的主机";
else
pingRst = strRst;
p.Close();
return pingRst;
}
}
//==================================================================================================MyMath
///
/// 数学函数库(算法)
///
internal class MyMath
{
public static double GetMax(double[] Datas)
{
double Max = -9999;
try
{
if (Datas.Length == 1)
return Datas[0];
for (int i = 0; i < Datas.Length; i++)
{
Max = Math.Max(Datas[i], Max);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Max;
}
public static double GetMin(double[] Datas)
{
double Min = 9999;
try
{
if (Datas.Length == 1)
return Datas[0];
for (int i = 0; i < Datas.Length; i++)
{
Min = Math.Min(Datas[i], Min);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Min;
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址,从0开始
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int DataAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (byteData.Length < 10 + DataAddr * 2)
{
return -1;
}
else
{
int bitH = DataAddr * 2 + 9;
int bitL = DataAddr * 2 + 10;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
return -1;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int DataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > DataAddr)
{
//MessageBox.Show("错误:要读取的数据小于起始地址");
return -1;
}
if (byteData.Length < 9 + (DataAddr - startAddr) * 2)
{
return -1;
}
else
{
int bitH = (DataAddr - startAddr) * 2 + 9;
int bitL = (DataAddr - startAddr) * 2 + 10;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return -1;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0001) > 0;
case 1:
return (data & 0x0002) > 0;
case 2:
return (data & 0x0004) > 0;
case 3:
return (data & 0x0008) > 0;
case 4:
return (data & 0x0010) > 0;
case 5:
return (data & 0x0020) > 0;
case 6:
return (data & 0x0040) > 0;
case 7:
return (data & 0x0080) > 0;
case 8:
return (data & 0x0100) > 0;
case 9:
return (data & 0x0200) > 0;
case 10:
return (data & 0x0400) > 0;
case 11:
return (data & 0x0800) > 0;
case 12:
return (data & 0x1000) > 0;
case 13:
return (data & 0x2000) > 0;
case 14:
return (data & 0x4000) > 0;
case 15:
return (data & 0x8000) > 0;
default:
return false;
}
}
public static bool GetPlcBitH2Low(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0100) > 0;
case 1:
return (data & 0x0200) > 0;
case 2:
return (data & 0x0400) > 0;
case 3:
return (data & 0x0800) > 0;
case 4:
return (data & 0x1000) > 0;
case 5:
return (data & 0x2000) > 0;
case 6:
return (data & 0x4000) > 0;
case 7:
return (data & 0x8000) > 0;
case 8:
return (data & 0x0001) > 0;
case 9:
return (data & 0x0002) > 0;
case 10:
return (data & 0x0004) > 0;
case 11:
return (data & 0x0008) > 0;
case 12:
return (data & 0x0010) > 0;
case 13:
return (data & 0x0020) > 0;
case 14:
return (data & 0x0040) > 0;
case 15:
return (data & 0x0080) > 0;
default:
return false;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(byte[] byteData, int DataAddr, int index, int startAddr)
{
int Value = GetPlcData(byteData, DataAddr, startAddr);
bool bResult = GetPlcBit(Value, index);
return bResult;
}
public static bool GetPlcBitH2Low(byte[] byteData, int DataAddr, int index, int startAddr)
{
int Value = GetPlcData(byteData, DataAddr, startAddr);
bool bResult = GetPlcBitH2Low(Value, index);
return bResult;
}
///
/// 获取单精度浮点数(float)数据
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 数据正反序
///
public static float GetPlcSingle(byte[] byteData, int DataAddr, int startAddr, bool PositiveSequence = true)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > DataAddr)
{
return -1;
}
if (byteData.Length < 9 + (DataAddr - startAddr) * 2)
{
return -1;
}
else
{
float Result = -1;
int startBit = (DataAddr - startAddr) * 2 + 9;
byte[] arrLength = new byte[4];
arrLength[0] = byteData[startBit + 0];
arrLength[1] = byteData[startBit + 1];
arrLength[2] = byteData[startBit + 2];
arrLength[3] = byteData[startBit + 3];
if (PositiveSequence)
{
Result = BitConverter.ToSingle(arrLength, 0);
}
else
{
Result = BitConverter.ToSingle(arrLength.Reverse().ToArray(), 0);
}
Result = Convert.ToSingle(Math.Round(Result, 3));
return Result;
}
}
catch
{
return -1;
}
}
///
/// 获取字符串(string)
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 读取的地址数量(单位16)
/// 数据正反序
/// 转换为字符串类型,2=二进制,10=十进制,16=十六进制,其他=char字符串
///
public static string GetPlcString(byte[] byteData, int DataAddr, int startAddr, int DataNum, bool PositiveSequence = true, int strType = 0)
{
string Result = "";
try
{
if (byteData == null)
{
return Result;
}
if (startAddr > DataAddr + DataNum)
{
return Result;
}
if (byteData.Length < 9 + (DataAddr - startAddr) * 2)
{
return Result;
}
else
{
int startBit = (DataAddr - startAddr) * 2 + 9;
byte[] arrLength = new byte[DataNum * 2];
for (int i = 0; i < DataNum * 2; i++)
{
arrLength[i] = byteData[startBit + i];
}
if (!PositiveSequence)
{
arrLength = (byte[])arrLength.Reverse();
}
switch (strType)
{
case 2:
foreach (byte b in arrLength)
{
Result += ConvertBase.MyConvert.DtoB(b);
}
break;
case 10:
foreach (byte b in arrLength)
{
Result += b.ToString();
}
break;
case 16:
foreach (byte b in arrLength)
{
Result += b.ToString("X2");
}
break;
default:
foreach (byte b in arrLength)
{
Result += Convert.ToChar(b).ToString();
}
break;
}
return Result.Trim();
}
}
catch
{
return Result;
}
}
//======================================================================
///
/// 字节数组(byte 8位)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(byte[] Value)
{
ushort[] rtnValues;
byte[] bytes = Value;
int Length = bytes.Length / 2;
if (bytes.Length % 2 == 0)
{
rtnValues = new ushort[Length];
for (int i = 0; i < bytes.Length; i += 2)
{
rtnValues[i / 2] = BitConverter.ToUInt16(bytes, i);
}
}
else
{
rtnValues = new ushort[bytes.Length / 2 + 1];
for (int i = 0; i < bytes.Length - 1; i += 2)
{
rtnValues[i / 2] = BitConverter.ToUInt16(bytes, i);
}
rtnValues[bytes.Length / 2] = bytes[bytes.Length - 1];
}
return rtnValues;
}
///
/// 字符串(string)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(string Value)
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(Value);
ushort[] ushorts = GetushortsFromValue(bytes);
return ushorts;
}
///
/// 单精度小数(float 32位)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(float Value)
{
byte[] bytes = BitConverter.GetBytes(Value);
ushort[] ushorts = GetushortsFromValue(bytes);
return ushorts;
}
///
/// 双精度小数(double 64位)转化为ushort(16位)数组
///
public static ushort[] GetushortsFromValue(double Value)
{
byte[] bytes = BitConverter.GetBytes(Value);
ushort[] ushorts = GetushortsFromValue(bytes);
return ushorts;
}
//======================================================================
///
/// 字节数组(byte 8位)转化为short(16位)数组
///
public static short[] GetshortsFromValue(byte[] Value)
{
short[] rtnValues;
byte[] bytes = Value;
int Length = bytes.Length / 2;
if (bytes.Length % 2 == 0)
{
rtnValues = new short[Length];
for (int i = 0; i < bytes.Length; i += 2)
{
rtnValues[i / 2] = BitConverter.ToInt16(bytes, i);
}
}
else
{
rtnValues = new short[bytes.Length / 2 + 1];
for (int i = 0; i < bytes.Length - 1; i += 2)
{
rtnValues[i / 2] = BitConverter.ToInt16(bytes, i);
}
rtnValues[bytes.Length / 2] = bytes[bytes.Length - 1];
}
return rtnValues;
}
///
/// 字符串(string)转化为short(16位)数组
///
public static short[] GetshortsFromValue(string Value)
{
byte[] bytes = System.Text.Encoding.Default.GetBytes(Value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
///
/// 整形(int 32位)转化为short(16位)数组
///
public static short[] GetshortsFromValue(int Value)
{
byte[] bytes = BitConverter.GetBytes(Value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
///
/// 单精度小数(float 32位)转化为short(16位)数组
///
public static short[] GetshortsFromValue(float Value)
{
byte[] bytes = BitConverter.GetBytes(Value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
///
/// 双精度小数(double 64位)转化为ushort(16位)数组
///
public static short[] GetshortsFromValue(double Value)
{
byte[] bytes = BitConverter.GetBytes(Value);
short[] shorts = GetshortsFromValue(bytes);
return shorts;
}
}
internal class CodeDfn
{
public const string BlankSpace = " ";
public const string strEnter = "\r\n";
}
internal class PlcMath
{
#region S7协议数据处理(以字节为基础)
public static bool GetS7BoolBit(byte data, int index)
{
switch (index)
{
case 0: return (data & 0x01) > 0;
case 1: return (data & 0x02) > 0;
case 2: return (data & 0x04) > 0;
case 3: return (data & 0x08) > 0;
case 4: return (data & 0x10) > 0;
case 5: return (data & 0x20) > 0;
case 6: return (data & 0x40) > 0;
case 7: return (data & 0x80) > 0;
default: return false;
}
}
public static bool GetS7BoolData(byte[] byteData, int DataAddr, int startAddr, int index)
{
byte data = GetS7ByteData(byteData, DataAddr, startAddr);
return GetS7BoolBit(data, index);
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static byte GetS7ByteData(byte[] byteData, int DataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return 0;
}
if (startAddr > DataAddr)
{
MessageBox.Show("错误:获取S7字节数据, 要读取的数据小于起始地址");
return 0;
}
if (byteData.Length < (DataAddr - startAddr))
{
MessageBox.Show("错误:获取S7字节数据, 要读取的偏移地址超出数组长度,偏移=" + (DataAddr - startAddr) + ", 数组长度=" + byteData.Length);
return 0;
}
else
{
int bit = DataAddr - startAddr;
return byteData[bit];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return 0;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static byte GetS7ByteData(byte[] byteData, int DataAddr)
{
try
{
if (byteData == null)
{
return 0;
}
if (byteData.Length < byteData.Length)
{
MessageBox.Show("获取S7字节数据,地址超出数组长度!", "警告");
return 0;
}
return byteData[DataAddr];
}
catch (Exception ex)
{
MessageBox.Show("Catch错误:获取S7字节数据" + ex.Message);
return 0;
}
}
public static int GetS7WordData(byte[] byteData, int DataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return -1;
}
//if (startAddr > DataAddr)
//{
// //MessageBox.Show("错误:要读取的数据小于起始地址");
// return -1;
//}
//if (byteData.Length < (DataAddr - startAddr) * 2)
//{
// return -1;
//}
//else
{
int bitH = (DataAddr - startAddr) * 2;
int bitL = (DataAddr - startAddr) * 2 + 1;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return -1;
}
}
///
/// 获取字符串(string)
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 读取的地址数量(单位16)
/// 数据正反序
/// 转换为字符串类型,2=二进制,10=十进制,16=十六进制,其他=char字符串
///
public static string GetS7StringData(byte[] byteData, int DataAddr, int startAddr, int DataNum, int strType = 0, bool PositiveSequence = true)
{
string Result = "";
try
{
if (byteData == null)
{
return Result;
}
if (startAddr > DataAddr + DataNum)
{
return Result;
}
if (byteData.Length < (DataAddr - startAddr))
{
return Result;
}
else
{
int startBit = (DataAddr - startAddr);
byte[] arrLength = new byte[DataNum];
for (int i = 0; i < DataNum; i++)
{
arrLength[i] = byteData[startBit + i];
}
if (!PositiveSequence)
{
arrLength = (byte[])arrLength.Reverse();
}
switch (strType)
{
case 2:
foreach (byte b in arrLength)
{
Result += ConvertBase.MyConvert.DtoB(b);
}
break;
case 10:
foreach (byte b in arrLength)
{
Result += b.ToString();
}
break;
case 16:
foreach (byte b in arrLength)
{
Result += b.ToString("X2");
}
break;
default:
foreach (byte b in arrLength)
{
if (b >= 32)
Result += Convert.ToChar(b).ToString();
}
break;
}
return Result.Trim();
}
}
catch
{
return Result;
}
}
///
/// 获取单精度浮点数(float)数据
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 数据正反序
///
public static float GetPlcSingleS7(byte[] byteData, int DataAddr, int startAddr, bool PositiveSequence)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > DataAddr)
{
return -1;
}
if (byteData.Length < (DataAddr - startAddr))
{
return -1;
}
else
{
float Result = -1;
int startBit = (DataAddr - startAddr);
byte[] arrLength = new byte[4];
arrLength[0] = byteData[startBit + 0];
arrLength[1] = byteData[startBit + 1];
arrLength[2] = byteData[startBit + 2];
arrLength[3] = byteData[startBit + 3];
if (PositiveSequence)
{
Result = BitConverter.ToSingle(arrLength, 0);
}
else
{
Result = BitConverter.ToSingle(arrLength.Reverse().ToArray(), 0);
}
Result = Convert.ToSingle(Math.Round(Result, 3));
return Result;
}
}
catch
{
return -1;
}
}
///
/// 获取双精度浮点数(double)数据
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 数据正反序
///
public static double GetPlcDoubleS7(byte[] byteData, int DataAddr, int startAddr, bool PositiveSequence)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > DataAddr)
{
return -1;
}
if (byteData.Length < (DataAddr - startAddr))
{
return -1;
}
else
{
double Result = -1;
int startBit = (DataAddr - startAddr);
byte[] arrLength = new byte[8];
arrLength[0] = byteData[startBit + 0];
arrLength[1] = byteData[startBit + 1];
arrLength[2] = byteData[startBit + 2];
arrLength[3] = byteData[startBit + 3];
arrLength[4] = byteData[startBit + 4];
arrLength[5] = byteData[startBit + 5];
arrLength[6] = byteData[startBit + 6];
arrLength[7] = byteData[startBit + 7];
if (PositiveSequence)
{
Result = BitConverter.ToDouble(arrLength, 0);
}
else
{
Result = BitConverter.ToDouble(arrLength.Reverse().ToArray(), 0);
}
Result = Convert.ToDouble(Math.Round(Result, 3));
return Result;
}
}
catch
{
return -1;
}
}
#endregion
#region ModbusTCP/FinsTCP协议数据处理(以字为基础)
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址,从0开始
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int DataAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (byteData.Length < DataAddr * 2)
{
return -1;
}
else
{
int bitH = DataAddr * 2;
int bitL = DataAddr * 2 + 1;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
return -1;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static byte GetPlcByteData(byte[] byteData, int DataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return 0;
}
if (startAddr > DataAddr)
{
//MessageBox.Show("错误:要读取的数据小于起始地址");
return 0;
}
//if (byteData.Length < (DataAddr - startAddr) * 2)
if (byteData.Length < (DataAddr - startAddr))
{
return 0;
}
else
{
int bit = DataAddr - startAddr;
return byteData[bit];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return 0;
}
}
///
/// 获取PLC读取地址数据(从起始地址偏移)
///
/// 数据数组
/// PLC读取地址
/// PLC读取起始地址
/// 返回整形数据或-1
public static int GetPlcData(byte[] byteData, int DataAddr, int startAddr)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > DataAddr)
{
//MessageBox.Show("错误:要读取的数据小于起始地址");
return -1;
}
if (byteData.Length < (DataAddr - startAddr) * 2)
{
return -1;
}
else
{
int bitH = (DataAddr - startAddr) * 2;
int bitL = (DataAddr - startAddr) * 2 + 1;
return byteData[bitH] * 256 + byteData[bitL];
}
}
catch
{
//MessageBox.Show("Catch错误:" + ex.Message);
return -1;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0001) > 0;
case 1:
return (data & 0x0002) > 0;
case 2:
return (data & 0x0004) > 0;
case 3:
return (data & 0x0008) > 0;
case 4:
return (data & 0x0010) > 0;
case 5:
return (data & 0x0020) > 0;
case 6:
return (data & 0x0040) > 0;
case 7:
return (data & 0x0080) > 0;
case 8:
return (data & 0x0100) > 0;
case 9:
return (data & 0x0200) > 0;
case 10:
return (data & 0x0400) > 0;
case 11:
return (data & 0x0800) > 0;
case 12:
return (data & 0x1000) > 0;
case 13:
return (data & 0x2000) > 0;
case 14:
return (data & 0x4000) > 0;
case 15:
return (data & 0x8000) > 0;
default:
return false;
}
}
public static bool GetPlcBitH2Low(int data, int index)
{
switch (index)
{
case 0:
return (data & 0x0100) > 0;
case 1:
return (data & 0x0200) > 0;
case 2:
return (data & 0x0400) > 0;
case 3:
return (data & 0x0800) > 0;
case 4:
return (data & 0x1000) > 0;
case 5:
return (data & 0x2000) > 0;
case 6:
return (data & 0x4000) > 0;
case 7:
return (data & 0x8000) > 0;
case 8:
return (data & 0x0001) > 0;
case 9:
return (data & 0x0002) > 0;
case 10:
return (data & 0x0004) > 0;
case 11:
return (data & 0x0008) > 0;
case 12:
return (data & 0x0010) > 0;
case 13:
return (data & 0x0020) > 0;
case 14:
return (data & 0x0040) > 0;
case 15:
return (data & 0x0080) > 0;
default:
return false;
}
}
///
/// 获取字节的某一位
///
/// 从0开始
///
public static bool GetPlcBit(byte[] byteData, int DataAddr, int index, int startAddr)
{
int Value = GetPlcData(byteData, DataAddr, startAddr);
bool bResult = GetPlcBit(Value, index);
return bResult;
}
public static bool GetPlcBitH2Low(byte[] byteData, int DataAddr, int index, int startAddr)
{
int Value = GetPlcData(byteData, DataAddr, startAddr);
bool bResult = GetPlcBitH2Low(Value, index);
return bResult;
}
///
/// 获取单精度浮点数(float)数据
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 数据正反序
///
public static float GetPlcSingle(byte[] byteData, int DataAddr, int startAddr, bool PositiveSequence)
{
try
{
if (byteData == null)
{
return -1;
}
if (startAddr > DataAddr)
{
return -1;
}
if (byteData.Length < (DataAddr - startAddr) * 2)
{
return -1;
}
else
{
float Result = -1;
int startBit = (DataAddr - startAddr) * 2;
byte[] arrLength = new byte[4];
arrLength[0] = byteData[startBit + 0];
arrLength[1] = byteData[startBit + 1];
arrLength[2] = byteData[startBit + 2];
arrLength[3] = byteData[startBit + 3];
if (PositiveSequence)
{
Result = BitConverter.ToSingle(arrLength, 0);
}
else
{
Result = BitConverter.ToSingle(arrLength.Reverse().ToArray(), 0);
}
Result = Convert.ToSingle(Math.Round(Result, 3));
return Result;
}
}
catch
{
return -1;
}
}
///
/// 获取字符串(string)
///
/// PLC读取总数据
/// 获取数据的地址
/// PLC起始地址
/// 读取的地址数量(单位16)
/// 数据正反序
/// 转换为字符串类型,2=二进制,10=十进制,16=十六进制,其他=char字符串
///
public static string GetPlcString(byte[] byteData, int DataAddr, int startAddr, int DataNum, int strType = 0, bool PositiveSequence = true)
{
string Result = "";
try
{
if (byteData == null)
{
return Result;
}
if (startAddr > DataAddr + DataNum)
{
return Result;
}
if (byteData.Length < (DataAddr - startAddr) * 2)
{
return Result;
}
else
{
int startBit = (DataAddr - startAddr) * 2;
byte[] arrLength = new byte[DataNum * 2];
for (int i = 0; i < DataNum * 2; i++)
{
arrLength[i] = byteData[startBit + i];
}
if (!PositiveSequence)
{
arrLength = (byte[])arrLength.Reverse();
}
switch (strType)
{
case 2:
foreach (byte b in arrLength)
{
Result += ConvertBase.MyConvert.DtoB(b);
}
break;
case 10:
foreach (byte b in arrLength)
{
Result += b.ToString();
}
break;
case 16:
foreach (byte b in arrLength)
{
Result += b.ToString("X2");
}
break;
default:
foreach (byte b in arrLength)
{
if (b >= 32)
Result += Convert.ToChar(b).ToString();
}
break;
}
return Result.Trim();
}
}
catch
{
return Result;
}
}
#endregion
}
public static class StringChange
{
#region 数据类型转换函数
public static byte[] Swap16Bytes(byte[] OldU16)
{
byte[] ReturnBytes = new byte[2];
ReturnBytes[1] = OldU16[0];
ReturnBytes[0] = OldU16[1];
return ReturnBytes;
}
public static bool CompareBytes(byte[] byteA, byte[] byteB, int iLen)
{
for (int i = 0; i < iLen; i++)
{
if (byteA[i] != byteB[i])
{
return false;
}
}
return true;
}
///
/// 16进制字符串转换成btye数组
///
/// 16进制字符串
///
public static byte[] HexStrTorbytes(string strHex)//e.g. " 01 01" ---> { 0x01, 0x01}
{
strHex = strHex.Replace(" ", "");
if ((strHex.Length % 2) != 0)
strHex += " ";
byte[] returnBytes = new byte[strHex.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(strHex.Substring(i * 2, 2), 16);
return returnBytes;
}
///
/// 二进制字符串转换成16进制字符串
///
/// 二进制字符串
/// 16进制字符串
public static string Binary2HexString(string strerjinzhi)
{
string str = "";
str = string.Format("{0:x}", Convert.ToInt32(strerjinzhi, 2));
return str;
}
///
/// 西门子16进制字符串转换成2进制的二维数组
///
/// 16进制字符串
/// 19:8的二维数组
public static string[,] HexString2BinString(string hexString)
{
string[,] strTestData = new string[19, 8];
for (int i = 0; i < hexString.Length / 2; i++)
{
string tempRes = string.Empty;
foreach (char c in hexString.Substring(i * 2, 2))
{
int v = Convert.ToInt32(c.ToString(), 16);
int v2 = int.Parse(Convert.ToString(v, 2));
// 去掉格式串中的空格,即可去掉每个4位二进制数之间的空格,
tempRes += string.Format("{0:d4}", v2);
}
int k = 0;
for (int j = tempRes.Length - 1; j >= 0; j--)
{
strTestData[i, k] = tempRes[j].ToString();
k++;
}
}
return strTestData;
}
///
/// 海德汉16进制字符串转换成2进制的二维数组 例如: 0X42 传入十六进制字符串42 (0100 0010), 返回二维数组(0100 0010)
///
/// 16进制字符串
/// 21:8的二维数组
public static string[,] HeidenhainHexString2BinString(string hexString)
{
string[,] strTestData = new string[23, 8];
for (int i = 0; i < hexString.Length / 2; i++)
{
string tempRes = string.Empty;
foreach (char c in hexString.Substring(i * 2, 2))
{
int v = Convert.ToInt32(c.ToString(), 16);
int v2 = int.Parse(Convert.ToString(v, 2));
// 去掉格式串中的空格,即可去掉每个4位二进制数之间的空格,
tempRes += string.Format("{0:d4}", v2);
}
int k = 0;
for (int j = tempRes.Length - 1; j >= 0; j--)
{
strTestData[i, k] = tempRes[j].ToString();
k++;
}
}
return strTestData;
}
///
/// byte数组转换成字符串 带空格隔开
///
/// byte数组
/// 长度
/// string
public static string bytesToHexStr(byte[] bytes, int iLen)//e.g. { 0x01,0x01} ---> " 01 01"
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < iLen; i++)
{
returnStr += bytes[i].ToString("X2") + " ";
}
}
return returnStr;
}
///
/// byte数组转换成字符串 不带空格
///
/// byte数组
/// 长度
/// string
public static string bytesToHexStrWithoutSpace(byte[] bytes, int iLen)//e.g. { 0x01,0x01} ---> " 0101"
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < iLen; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
///
/// 计算CRC
///
/// byte数组
/// 长度
/// CRC校验和
public static byte CalculateCRC(byte[] pMessage, int iLength)
{
int i = 0;
byte iVerify = 0;
for (i = 0; i < iLength; i++)
{
iVerify = (byte)(iVerify + pMessage[i]);
}
return iVerify;
}
public static string StringToHexString(string s, Encoding encode)
{
byte[] b = encode.GetBytes(s); //按照指定编码将string编程字节数组
string result = string.Empty;
for (int i = 0; i < b.Length; i++) //逐字节变为16进制字符,以%隔开
{
result += "%" + Convert.ToString(b[i], 16);
}
return result;
}
public static string HexStringToString(string hs, Encoding encode)
{
//以%分割字符串,并去掉空字符
string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++)
{
b[i] = Convert.ToByte(chars[i], 16);
}
//按照指定编码将字节数组变为字符串
return encode.GetString(b);
}
public static short SwapInt16(this short n)
{
return (short)(((n & 0xff) << 8) | ((n >> 8) & 0xff));
}
public static ushort SwapUInt16(this ushort n)
{
return (ushort)(((n & 0xff) << 8) | ((n >> 8) & 0xff));
}
public static int SwapInt32(this int n)
{
return (int)(((SwapInt16((short)n) & 0xffff) << 0x10) |
(SwapInt16((short)(n >> 0x10)) & 0xffff));
}
public static uint SwapUInt32(this uint n)
{
return (uint)(((SwapUInt16((ushort)n) & 0xffff) << 0x10) |
(SwapUInt16((ushort)(n >> 0x10)) & 0xffff));
}
public static long SwapInt64(this long n)
{
return (long)(((SwapInt32((int)n) & 0xffffffffL) << 0x20) |
(SwapInt32((int)(n >> 0x20)) & 0xffffffffL));
}
public static ulong SwapUInt64(this ulong n)
{
return (ulong)(((SwapUInt32((uint)n) & 0xffffffffL) << 0x20) |
(SwapUInt32((uint)(n >> 0x20)) & 0xffffffffL));
}
#endregion
}
public static class JsonHelper
{
///
/// 对象转成JSON 格式字符串
///
/// 对象
/// JSON格式的字符串
public static string ObjectToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}
///
/// 解析JSON字符串生成对象实体
///
/// 对象类型
/// json字符串
/// 对象实体
public static T DeserializeJsonToObject(string json) where T : class
{
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
///
/// 解析JSON数组生成对象实体集合
///
/// 对象类型
/// json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])
/// 对象实体集合
public static List DeserializeJsonToList(string json) where T : class
{
Newtonsoft.Json.JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List));
List list = o as List;
return list;
}
///
/// 数据表转键值对集合 把DataTable转成 List集合, 存每一行 集合中放的是键值对字典,存每一列
///
/// 数据表
/// 哈希表数组
public static List> DataTableToList(DataTable dt)
{
List> list = new List>();
foreach (DataRow dr in dt.Rows)
{
Dictionary dic = new Dictionary();
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
list.Add(dic);
}
return list;
}
///
/// 数据集转键值对数组字典
///
/// 键值对数组字典
public static Dictionary>> DataSetToDic(DataSet ds)
{
Dictionary>> result = new Dictionary>>();
foreach (DataTable dt in ds.Tables)
result.Add(dt.TableName, DataTableToList(dt));
return result;
}
///
/// 数据表转JSON
///
/// 数据表
/// JSON字符串
public static string DataTableToJson(DataTable dt)
{
return ObjectToJson(DataTableToList(dt));
}
///
/// JSON文本转对象,泛型方法 常用
///
/// 类型
/// JSON文本
/// 指定类型的对象
public static T JsonToObject(string jsonText)
{
return JsonConvert.DeserializeObject(jsonText);
}
///
/// 将JSON文本转换为数据表数据
///
/// JSON文本
/// 数据表字典
public static Dictionary>> TablesDataFromJson(string jsonText)
{
return JsonToObject>>>(jsonText);
}
///
/// 将JSON文本转换成数据行
///
/// JSON文本
/// 数据行的字典
public static Dictionary DataRowFromJson(string jsonText)
{
return JsonToObject>(jsonText);
}
}
}