下位机数据接收十六进制写入文件

项目:实现can总线传感器  QN1161 测试上位机

要求:需要将接收的到数据写入到文件中

格式: 时间 + CAN ID + 数据; 如: 2015/4/22 11:45:18 0xF5F4EB18 03 EC 0D 0B 00 02 00 00

 

一、写入文件(追加方式)

/// <summary>
/// 写入文件
/// </summary>
public void WriteFile(string strInfo)
{
    FileStream fs = new FileStream("D:\\data.txt", FileMode.Append);
    //获得字节数组
    byte[] data = System.Text.Encoding.Default.GetBytes(strInfo);
    //开始写入
    fs.Write(data, 0, data.Length);
    //清空缓冲区、关闭流
    fs.Flush();
    fs.Close();
}

二、CAN ID地址转换

/// <summary>
/// CAN id 地址转 HEX String
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string _byteToHexStr(byte[] bytes)
{
      string returnStr = "";
      if (bytes != null)
      {
            for (int i = 0; i < bytes.Length; i++)
            {
                returnStr += bytes[i].ToString("X2");
            }
       }
       return returnStr;
} 

三、数据转 HEX string

/// <summary> 
/// 字节数组转16进制字符串 
/// </summary> 
/// <param name="bytes"></param> 
/// <returns></returns> 
public static string byteToHexStr(byte[] bytes)
{
    string returnStr = "";
    if (bytes != null)
    {
        for (int i = 0; i < bytes.Length; i++)
        {
           returnStr += bytes[i].ToString("X2") + " ";
        }
    }
    return returnStr;
}

 

四、使用

byte[] bpara  =System.BitConverter.GetBytes(tmp.devID);
string devIDstring = "0x" + _byteToHexStr(bpara);
WriteFile(DateTime.Now.ToString() + " " + devIDstring + " " + byteToHexStr(tmp.recvData) + "\r\n");  //写入文件

有点乱的,可以整理整理,还不错,希望对你有帮助,

耶稣爱你!!

posted @ 2015-04-22 11:56  仆人  阅读(566)  评论(0编辑  收藏  举报