TCP/IP通信或串口通信数据类型转换
2016-09-27 15:39
543 查看
/// <summary> /// string转换为byte[]数组 /// </summary> /// <param name="str"></param> /// <returns></returns> public static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } /// <summary> /// byte[]数组转换为strng /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } /// <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; } /// <summary> /// byte转换为string /// </summary> /// <param name="bytes"></param> /// <param name="len"></param> /// <returns></returns> public static string ToHexString(byte[] bytes, int len) { return ToHexString(bytes, 0, len); } public static string ToHexString(byte[] bytes, int start, int len) { string strReturn = ""; for (int i = start; i < (start + len); i++) { byte bt = bytes[i]; strReturn += bt.ToString("x2"); } return strReturn; } /// <summary> /// 16进制转ASCII /// </summary> /// <param name="Msg"></param> /// <returns></returns> public static string HexToASCII(string Msg) { byte[] buff = new byte[Msg.Length / 2]; string Message = ""; for (int i = 0; i < buff.Length; i++) { buff[i] = byte.Parse(Msg.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } System.Text.Encoding chs = System.Text.Encoding.ASCII; Message = chs.GetString(buff); return Message; } /// <summary> /// 字符串转16进制字节数组 /// </summary> /// <param name="hexString"></param> /// <returns></returns> private static byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } /// <summary> /// 16进制转换为byte[] /// </summary> /// <param name="hexStr"></param> /// <returns></returns> public static byte[] ToByesByHex(string hexStr) { int len = hexStr.Length; byte[] data = new byte[len / 2]; for (int k = 0; k < data.Length; k++) { data[k] = Convert.ToByte(hexStr.Substring(k * 2, 2), 16); //k = k* 2; } return data; } /// <summary> /// 从汉字转换到16进制 /// </summary> /// <param name="s"></param> /// <param name="charset">编码,如"utf-8","gb2312"</param> /// <param name="fenge">是否每字符用逗号分隔</param> /// <returns></returns> public static string ToHex(string s, string charset, bool fenge) { if ((s.Length % 2) != 0) { s += " ";//空格 //throw new ArgumentException("s is not valid chinese string!"); } System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); byte[] bytes = chs.GetBytes(s); string str = ""; for (int i = 0; i < bytes.Length; i++) { str += string.Format("{0:X}", bytes[i]); if (fenge && (i != bytes.Length - 1)) { str += string.Format("{0}", ","); } } return str.ToLower(); } ///<summary> /// 从16进制转换成汉字 /// </summary> /// <param name="hex"></param> /// <param name="charset">编码,如"utf-8","gb2312"</param> /// <returns></returns> public static string UnHex(string hex, string charset) { if (hex == null) throw new ArgumentNullException("hex"); hex = hex.Replace(",", ""); hex = hex.Replace("\n", ""); hex = hex.Replace("\\", ""); hex = hex.Replace(" ", ""); if (hex.Length % 2 != 0) { hex += "20";//空格 } // 需要将 hex 转换成 byte 数组。 byte[] bytes = new byte[hex.Length / 2]; for (int i = 0; i < bytes.Length; i++) { try { // 每两个字符是一个 byte。 bytes[i] = byte.Parse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } catch { // Rethrow an exception with custom message. throw new ArgumentException("hex is not a valid hex number!", "hex"); } } System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); return chs.GetString(bytes); } /// <summary> /// Unicode转汉字 /// </summary> /// <param name="text"></param> /// <returns></returns> public static string UnicodeToGB(string text) { System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})"); if (mc != null && mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m2 in mc) { string v = m2.Value; string word = v.Substring(2); byte[] codes = new byte[2]; int code = Convert.ToInt32(word.Substring(0, 2), 16); int code2 = Convert.ToInt32(word.Substring(2), 16); codes[0] = (byte)code2; codes[1] = (byte)code; text = text.Replace(v, Encoding.Unicode.GetString(codes)); } } else { } return text; } public static string unicodetogbx(string text) { System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})"); string a = text.Replace("\\u", ""); char[] arr = new char[mc.Count]; for (int i = 0; i < arr.Length; i++) { arr[i] = (char)Convert.ToInt32(a.Substring(i * 4, 4), 16); } string c = new string(arr); return c; } /// <summary> /// Unicode转汉字(测试通过) /// </summary> /// <param name="text"></param> /// <returns></returns> public static string UnicodeToCn(string text) { string cd = text; string cd2 = cd.Replace(" ", ""); cd2 = cd2.Replace("\r", ""); cd2 = cd2.Replace("\n", ""); cd2 = cd2.Replace("\r\n", ""); cd2 = cd2.Replace("\t", ""); if (cd2.Length % 4 != 0) { //MessageBox.Show("Unicode编码为双字节,请删多或补少!确保是二的倍数。"); return ""; } else { int len = cd2.Length / 2; byte[] b = new byte[len]; for (int i = 0; i < cd2.Length; i += 2) { string bi = cd2.Substring(i, 2); b[i / 2] = (byte)Convert.ToInt32(bi, 16); } string o = Encoding.Unicode.GetString(b); //textBox2.Text = o; return o; } } /// <summary> /// 字符串转为UniCode码字符串 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string StringToUnicode(string s) { char[] charbuffers = s.ToCharArray(); byte[] buffer; StringBuilder sb = new StringBuilder(); for (int i = 0; i < charbuffers.Length; i++) { buffer = System.Text.Encoding.Unicode.GetBytes(charbuffers[i].ToString()); sb.Append(String.Format("//u{0:X2}{1:X2}", buffer[1], buffer[0])); } return sb.ToString(); } /// <summary> /// Unicode字符串转为正常字符串 /// </summary> /// <param name="srcText"></param> /// <returns></returns> public static string UnicodeToString(string srcText) { string dst = ""; string src = srcText; int len = srcText.Length / 6; for (int i = 0; i <= len - 1; i++) { string str = ""; str = src.Substring(0, 6).Substring(2); src = src.Substring(6); byte[] bytes = new byte[2]; bytes[1] = byte.Parse(int.Parse(str.Substring(0, 2), NumberStyles.HexNumber).ToString()); bytes[0] = byte.Parse(int.Parse(str.Substring(2, 2), NumberStyles.HexNumber).ToString()); dst += Encoding.Unicode.GetString(bytes); } return dst; }
相关文章推荐
- DTU(用于将串口数据转换为IP数据或将IP数据转换为串口数据通过无线通信网络进行传送的无线终端设备)
- 提供多种类型IP数据业务的通信系统d 第三代移动通信系统
- TCP/IP通信或串口通信数据校验
- C#与单片机通信中遇到的数据类型转换
- java socket tcp/ip基本数据类型编解码【高序字节 低序字节】
- ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml) 用javascript在客户端删除某一个cookie键值对 input点击链接另一个页面,各种操作。 C# 往线程里传参数的方法总结 TCP/IP 协议 用C#+Selenium+ChromeDriver 生成我的咕咚跑步路线地图 (转)值得学习百度开源70+项目
- STM32串口通信代码、ASCII码、XU4串口通信,printf只会转换为无符号类型,linux下的串口通信程序
- 各数据类型转换byte数组(方便java和c++的网络通信)
- 生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间
- java和c通信相关的数据类型转换
- QT5 串口数据类型转换
- 网络通信中,DELPHI的string类型数据转换为C++字符串发送的一个陷阱
- IOS 蓝牙通信各种数据类型之间的转换
- 串口数据类型转换
- 图解TCP/IP(四)——TCP通信之发送数据基本点
- 利用TCP/IP模型理解数据通信过程
- 【C#串口编程计划】通信协议解析 -- byte[]与常用类型的转换
- 实现基于TCP/IP的多串口转换网关
- iOS 一个在UDP/TCP通信时,对16进制、10进制、NSData等数据之间的转换发送等处理的工具类库,一行代码将16进制字符串轻松转换成UDP需要的指令数据
- JAVA基础二(java中的注释、ava编程语法基础、java数据类型、数据类型的转换、变量、运算符、分支语句、循环语句)