C#搞工控的一些代码

首先工控项目都会用到:
using System.Runtime.InteropServices;
1、字节转化为单精度浮点数
2、单精度转成字节
3、使用结构体
4、使用动态链接库
5、ASCCII码字符转成16进制数
6、字符转ASCII码,ASCII码转字符
7、字符串转成字符数组
8、整形数据与字节数组相互转换
9、ASCII码的使用,适用于串口通信
10、c#获得时间和路径 
 
 
 
 
1、字节转化为单精度浮点数
           //byte[] retdata = new byte[] { 0x00, 0x00, 0x7A, 0x43 }; //43 7A 00 00 是250,在这里要倒过来写
            byte[] r;
            r=new byte[4];
            r[3] = 0x43;
            r[2] = 0xac;
            r[1] = 0x00;
            r[0] = 0x00;
            textBox1.Text = BitConverter.ToSingle(r, 0).ToString ();
 
2、单精度转成字节
            float floatvalue;
            floatvalue = 2500;
            byte[] b = BitConverter.GetBytes(floatvalue );
            textBox1.Text =Convert.ToString(b[3],16)+" "+Convert.ToString(b[2],16)+" "+Convert.ToString(b[1],16)+" "+Convert.ToString(b[0],16);
 
3、使用结构体
   (1)先引用命名空间
        using System.Runtime.InteropServices;
   (2)在public partial class Form1 : Form
          { 
        中声明结构体类型。例如://注意代码的位置
        [StructLayout(LayoutKind.Sequential)]  //不写这个也行,默认的内存排列就是Sequential,也就是按成员的先后顺序排列.
        public struct PVCI_INIT_CONFIG
        {
            public uint AccCode;
            public uint AccMask;
            public uint Reserved;
            public byte Filter;
            public byte kCanBaud;
            public byte Timing0;
            public byte Timing1;
            public byte Mode;
            public byte CanRx_IER;
        }
    (3)在需要使用的地方定义:
         形式1:s x;
                x.a = 0x55;
                x.b = 0x66;
         形式2:PVCI_INIT_CONFIG[] config = new PVCI_INIT_CONFIG[1];  //定义一个结构体数组
                config[0].AccCode = 0x80000008;
                config[0].AccMask = 0xFFFFFFFF;
                config[0].Reserved = 204;
                config[0].Filter = 0;
                config[0].kCanBaud = 12;  //500k
                config[0].Timing0 = 0x00;
                config[0].Timing1 = 0x1C;
                config[0].CanRx_IER = 1; //Enable CAN reveive
                config[0].Mode = 0;
 
4、使用动态链接库
        有些DLL有依赖文件,例如:吉阳CANUSB的,和DLL相关的有两个VCI_CAN文件和一个SiUSBXp.dll文件。将所有相关文件拷贝到bin\debug中和exe文件在一个文件中。
        using System.Runtime.InteropServices;
        在窗体类中public partial class Form1 : Form
        声明就可以用   
        [DllImport("VCI_CAN.dll",EntryPoint = "VCI_OpenDevice")]
        public static extern int VCI_OpenDevice(uint Devtype, uint Devindex, uint Reserved);
 
 
5、ASCCII码字符转成16进制数
                 //这个在串口通信有实际应用
//如9的ASCCII码是57,将9的ASCCII传进函数,然后57-0x30就是数字9
//再如F的ASCCI码是70,70-'A'=70-65=5,然后5+10就是15也就是F表示的数字
        public int HexChar(char c)
        {
            if ((c >= '0') && (c <= '9'))
                return c - 0x30;
            else if ((c >= 'A') && (c <= 'F'))
                return c - 'A' + 10;
            else if ((c >= 'a') && (c <= 'f'))
                return c - 'a' + 10;
            else
                return 0x10;
        }
        //这个将FE之类的字符串转成数字
        public int Str2Hex(string str)
        {
            int len = str.Length;
            if (len == 2)
            {
                int a = HexChar(str[0]);
                int b = HexChar(str[1]);
                if (a == 16 || b == 16)
                {
                    MessageBox.Show("format error!");
                    return 256;
                }
                else
                {
                    return a * 16 + b;
 
                }
 
            }
            else
            {
                MessageBox.Show("len must be 2");
                return 256;
            }
        }
       //可以这样使用,强制转换为字节型,并以字符串显示为254
       textBox1.Text = Convert.ToString((byte)Str2Hex("FE"));
       //这样就显示FE了
       textBox1.Text = Convert.ToString((byte)Str2Hex("FE"),16);
 
6、字符转ASCII码,ASCII码转字符 
      public static int Asc(string character)
  {
   if (character.Length == 1)
   {
    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
    int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
    return (intAsciiCode);
   }
   else
   {
    throw new Exception("Character is not valid.");
   } 
 
  } 
 
ASCII码转字符: 
单个字符
public static string Chr(int asciiCode)
  {
   if (asciiCode >= 0 && asciiCode <= 255)
   {
    System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
    byte[] byteArray = new byte[] { (byte)asciiCode };
    string strCharacter = asciiEncoding.GetString(byteArray);
    return (strCharacter);
   }
   else
   {
    throw new Exception("ASCII Code is not valid.");
   }
  } 
Excel专用
/// <summary>
        /// ASCII码转字符串(转换为Excel列的形式:A/B/C...AA/AB/AC...BA/BB/......)
        /// </summary>
        /// <param name="asciiCode">最大数字255(即Excel最末列IV)</param>
        /// <returns></returns>
        public static string Chr(int asciiCode)
        {
            if (asciiCode > 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                string strCharacter = string.Empty;
                byte[] byteArray = null;
                int division = (asciiCode - 64) / 26;
                int mod = (asciiCode - 64) % 26;
                if (mod == 0)
                {
                    division = division - 1;
                    mod = 26;
                }
 
                if ((division == 0) && (mod <= 26))
                {
                    byteArray = new byte[] { (byte)(mod + 64) };
                    strCharacter = strCharacter + asciiEncoding.GetString(byteArray);
                }
                else
                {
                    byteArray = new byte[] { (byte)(division + 64) };
                    strCharacter = strCharacter + asciiEncoding.GetString(byteArray);
 
                    byteArray = new byte[] { (byte)(mod + 64) };
                    strCharacter = strCharacter + asciiEncoding.GetString(byteArray);
                }
 
                return strCharacter;
            }
            else
            {
                return "ASCII Code is not valid.";
            }
        }
 
7、字符串转成字符数组
            string ss;
            ss = "hello world";
            char[] sx=ss.ToCharArray();
            int i;
            for (i = 0; i < sx.Length; i++)
            {
                textBox1.Text = textBox1.Text + " " + sx[i];
            }
 
 
8、整形数据与字节数组相互转换
            
            例如:吉阳CAN的ID号移位问题
            int id;
            id = 0x088090C1<<3;         
            byte[] sID = BitConverter.GetBytes(id);
            textBox1.Text = Convert.ToString(sID[3], 16) + " " + Convert.ToString(sID[2], 16) + " " + Convert.ToString(sID[1], 16) + " " + Convert.ToString(sID[0], 16) +" ";
            //将字节数组组合成32位整形
            int rID=0x00000000;
            rID = (sID[3] << 24) | (sID[2] << 16)|(sID[1]<<8)|sID[0];
            rID = rID >> 3;
             
9、ASCII码的使用,适用于串口通信
             char x = (char)59;     //ASCII码是59
            textBox1.Text = "hello" + x.ToString()+(char)32+"world";  //asccii码32是空格
            //写成数组形式
            char[] str = { (char)45,(char)48,(char)100 };  //(char)77 就是ASCII码77的 强制转为字符
            textBox1.Text = str[0].ToString() + str[1].ToString() + str[2].ToString(); //用在串口发送上比较合适
 
 
10、c#获得时间和路径             
//  textBox1.Text = DateTime.Now .ToString ()+":"+DateTime.Now.Millisecond .ToString() ; //时间,精确到毫秒
            //  textBox1.Text = Environment.CurrentDirectory.ToString();  //当前路径
            //  textBox1.Text = Environment.TickCount.ToString();  //获得系统启动经过的毫秒数
            //  System.Threading.Thread.Sleep(1000);  //暂停1秒

 

posted on 2017-03-11 16:36  大西瓜3721  阅读(1351)  评论(0编辑  收藏  举报

导航