using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace demo.ClassHelper.TranslateFormat { class ConvertHelper { public const Byte ASCII_0 = 48; public const Byte ASCII_9 = 57; public const Byte ASCII_A = 65; public const Byte ASCII_F = 70; public const Byte ASCII_Z = 90; public const Byte ASCII_a = 97; public const Byte ASCII_f = 102; public const Byte ASCII_z = 122; /// /// 字节转换为字符串 /// /// /// public static String ByteToHexChar(Byte val) { return val.ToString("X2"); } /// /// 字节转换为字符串 /// /// /// public static String ByteToBitString(Byte val) { if (val == 0) { return "00000000"; } if (val == 255) { return "11111111"; } String ret = String.Empty; Int32 bitval = 0; for (int bitidx = 7; bitidx > -1; --bitidx) { bitval = val & (1 << bitidx); if (bitval > 0) { ret = ret + "1"; } else { ret = ret + "0"; } } return ret; } /// /// 2个HEX字符转换为1个字节数组 /// /// "A1" /// 161 /// public static Boolean HexStringToByte(String hexstr, out Byte byteval) { byteval = 0; if (hexstr.Length != 2) { return false; } byteval = Convert.ToByte(hexstr, 16); return true; } /// /// HEX字符串转换为字节数组 /// /// /// /// public static Boolean HexStringToBytes(String hexstr, out Byte[] bytes) { bytes = null; if ((hexstr == null) || (hexstr.Length < 2)) { return false; } if (hexstr.Length % 2 == 1) { return false; } int bytelen = hexstr.Length / 2; if (bytelen < 1) { return false; } bytes = new Byte[bytelen]; String curbytestr = String.Empty; for (int bidx = 0; bidx < bytelen; bidx++) { curbytestr = hexstr.Substring(bidx * 2, 2); //数字的进制,它必须是 2、8、10和16. bytes[bidx] = Convert.ToByte(curbytestr, 16); } if (bytes == null || bytes.Length < 1) { return false; } return true; } /// /// HEX字符串转换为字节数组 /// /// /// /// public static Boolean HexStringToBytesWithSplitter(String hexstr, out Byte[] bytes) { bytes = null; if (hexstr == null || hexstr.Length < 2) { return false; } int charidx = 0; StringBuilder strbuild = new StringBuilder(hexstr.Length); //对每个字符进行判断,过滤非法字符 while (charidx < hexstr.Length) { //A-65, F-70,a-97,f-102, 0-48 9-57 if ((hexstr[charidx] >= ConvertHelper.ASCII_0 && hexstr[charidx] <= ConvertHelper.ASCII_9) || (hexstr[charidx] >= ConvertHelper.ASCII_A && hexstr[charidx] <= ConvertHelper.ASCII_F) || (hexstr[charidx] >= ConvertHelper.ASCII_a && hexstr[charidx] <= ConvertHelper.ASCII_f)) { strbuild.Append(hexstr[charidx]); } charidx++; } String purehexstr = strbuild.ToString(); return HexStringToBytes(purehexstr, out bytes); } /// /// 字节数组转换为字符串 /// /// /// public static String BytesToHexString(Byte[] bytes) { if (bytes == null || bytes.Length < 1) { return String.Empty; } StringBuilder str = new StringBuilder(bytes.Length * 2); for (int i = 0; i < bytes.Length; i++) { str.Append(bytes[i].ToString("X2")); } return str.ToString(); } /// /// 字节数组转换为字符串 /// /// /// 待转换的首个字节下标 /// /// 每隔多少字节,就插入一个换行符.0表示不换行 /// public static String BytesToHexString(Byte[] bytes, Int32 start, Int32 len, Int32 eachlinebytes) { if (bytes == null || bytes.Length < 1 || start < 0 || len < 1 || start + len > bytes.Length) { return String.Empty; } Int32 curlinebytes = 0; StringBuilder str = new StringBuilder(bytes.Length * 2); for (int i = 0; i < len; i++) { str.Append(bytes[i + start].ToString("X2")); if (eachlinebytes > 0) { curlinebytes++; if (curlinebytes >= eachlinebytes) { str.Append(Environment.NewLine); curlinebytes = 0; } } } return str.ToString(); } /// /// 字节数组转换为带间隔符的字符串,显示用 /// /// /// 待转换的首个字节下标 /// /// /// 每隔多少字节,就插入一个换行符.0表示不换行 /// public static String BytesToHexString(Byte[] bytes, Int32 start, Int32 len, Char splitter, Int32 eachlinebytes) { if (bytes == null || bytes.Length < 1 || start < 0 || len < 1 || start + len > bytes.Length) { return String.Empty; } Int32 curlinebytes = 0; StringBuilder str = new StringBuilder(bytes.Length * 2); for (int i = 0; i < bytes.Length; i++) { str.Append(bytes[i + start].ToString("X2")); if ((Byte)(splitter) != 0) { str.Append(splitter); } if (eachlinebytes > 0) { curlinebytes++; if (curlinebytes >= eachlinebytes) { str.Append(Environment.NewLine); curlinebytes = 0; } } } str.Remove(str.Length - 1, 1); return str.ToString(); } /// /// 字节数组转换为ASCII字符串 /// /// /// public static String BytesToString(Byte[] bytes) { String ret = Encoding.Default.GetString(bytes); return ret; } /// /// 1个字节的BCD转换为HEX /// 0x12->12 /// /// BCD字节 /// Int32 public static Byte ByteBCDToHex(Byte bcd) { Byte result = (Byte)(bcd & 0x0F); //个位 bcd >>= 4; result += (Byte)(bcd * 10); //十位 return result; //返回结果 } /// /// 把数组里的每个字节,都从HEX 转换为BCD /// /// public static Boolean ByteArrayHexToBCD(Byte[] hexbytes, Int32 hexstart, Byte[] bcdbytes, Int32 bcdstart, Int32 len) { if (hexbytes == null || bcdbytes == null || hexbytes.Length < 1 || bcdbytes.Length < 1 || hexstart < 0 || bcdstart < 0 || hexstart + len > hexbytes.Length || bcdstart + len > bcdbytes.Length) { return false; } for (Int32 idx = 0; idx < len; ++idx) { bcdbytes[bcdstart + idx] = ByteHexToBCD(hexbytes[hexstart + idx]); } return true; } /// /// 把数组里的每个字节,都从BCD转换为HEX /// /// public static Boolean ByteArrayBCDToHex(Byte[] bcdbytes, Int32 bcdstart, Byte[] hexbytes, Int32 hexstart, Int32 len) { if (hexbytes == null || bcdbytes == null || hexbytes.Length < 1 || bcdbytes.Length < 1 || hexstart < 0 || bcdstart < 0 || hexstart + len > hexbytes.Length || bcdstart + len > bcdbytes.Length) { return false; } for (Int32 idx = 0; idx < len; ++idx) { hexbytes[hexstart + idx] = ByteBCDToHex(bcdbytes[bcdstart + idx]); } return true; } /// /// 1个字节的HEX转换为BCD /// 64->0x64 /// /// BCD字节 /// Int32 public static Byte ByteHexToBCD(Byte val) { //如果超过99,则转换99 if (val > 99) { return 0x99; } Byte lowval = (Byte)(val % 10);//个位 Byte highval = (Byte)((val / 10) % 10);//十位 Byte ret = (Byte)(lowval + (highval << 4)); return ret; } /// /// ASCII字符串转换为字节数组 /// /// /// /// public static Boolean StringToBytes(String asciistr, out Byte[] bytes) { bytes = Encoding.Default.GetBytes(asciistr); if (bytes == null || bytes.Length < 1) { return false; } return true; } /// /// Boolean 转换为 Int32 /// /// /// public static Int32 BooleanToInt32(Boolean bl) { return bl ? 1 : 0; } /// /// Boolean 转换为 Int32 的字符串 /// /// /// public static String BooleanToInt32String(Boolean bl) { return bl ? "1" : "0"; } /// /// Int32 转换为 Boolean /// /// /// public static Boolean Int32ToBoolean(Int32 intval) { return (intval == 0) ? false : true; } /// /// Int32 的字符串 转换为 Boolean /// /// /// public static Boolean Int32StringToBoolean(String intstr) { if (intstr.Length < 1) { return false; } return (intstr[0] == '0') ? false : true; } /// /// 各种枚举值转换为Int32String /// /// /// public static String Int32ToString(Int32 enumval) { return enumval.ToString(); } /// /// 使用指定间隔符,把字符串分割为多个子串,合并为List /// /// /// /// /// public static Boolean StringToIntArray(String rawdata, char splitter, ref Int32[] intarray) { List strlst = null; Boolean bl = StringToList(rawdata, splitter, ref strlst); if (!bl) { return false; } List intlist = new List(); Int32 val; for (int i = 0; i < strlst.Count; i++) { bl = Int32.TryParse(strlst[i], out val); if (bl) { intlist.Add(val); } } if (intlist.Count < 1) { return false; } intarray = intlist.ToArray(); return true; } /// /// 使用指定间隔符,把List合并为一个字符串 /// /// /// /// /// public static Boolean ListToString(List strlist, char splitter, out String result) { result = String.Empty; if ((strlist == null || strlist.Count < 1)) { return false; } foreach (String item in strlist) { result = result + item + splitter; } result = result.Remove(result.Length - 1, 1); return true; } ///// ///// 使用指定间隔符,把字符串分割为多个子串,合并为BindingList ///// ///// ///// ///// ///// //public static Boolean StringToBindingList(String rawdata, char splitter, out ObservableCollection strlist) //{ // strlist = new ObservableCollection(); // if (String.IsNullOrEmpty(rawdata)) // { // return false; // } // String[] ary = rawdata.Split(splitter); // if ((ary == null) || (ary.Length < 1)) // { // return false; // } // for (int i = 0; i < ary.Length; i++) // { // strlist.Add(ary[i]); // } // return true; //} ///// ///// 使用指定间隔符,把BindingList合并为一个字符串 ///// ///// ///// ///// ///// //public static Boolean BindingListToString(ObservableCollection strlist, char splitter, out String result) //{ // result = String.Empty; // if ((strlist == null || strlist.Count < 1)) // { // return false; // } // StringBuilder tmpstr = new StringBuilder(4096); // foreach (String item in strlist) // { // tmpstr.Append(item); // tmpstr.Append(splitter); // } // tmpstr.Remove(result.Length - 1, 1); // result = tmpstr.ToString(); // return true; //} /// /// 使用指定间隔符,把字符串分割为多个子串,合并为List /// /// /// /// /// public static Boolean StringToIntList(String rawdata, char splitter, ref List intlist) { List strlst = null; Boolean bl = StringToList(rawdata, splitter, ref strlst); if (!bl) { return false; } intlist = new List(); Int32 val; for (int i = 0; i < strlst.Count; i++) { bl = Int32.TryParse(strlst[i], out val); if (bl) { intlist.Add(val); } } return (intlist.Count > 0); } /// /// 使用指定间隔符,把字符串分割为多个子串,合并为List /// /// /// /// /// public static Boolean StringToList(String rawdata, char splitter, ref List strlist) { if (String.IsNullOrEmpty(rawdata)) { return false; } String[] ary = rawdata.Split(splitter); if ((ary == null) || (ary.Length < 1)) { return false; } if (strlist == null) { strlist = new List(); } strlist.AddRange(ary); return true; } /// /// 把字符串列表转换为Boolean数组 /// /// /// /// public static Boolean StringToBooleanArray(String boolliststr, ref Boolean[] boolary) { if (boolary == null) { return false; } Int32 len = (boolliststr.Length > boolary.Length) ? boolary.Length : boolliststr.Length; for (Int32 idx = 0; idx < len; ++idx) { boolary[idx] = (boolliststr[idx] == '0') ? false : true; } return true; } /// /// 把Boolean数组转换为字符串列表 /// /// /// /// public static String BooleanArrayToString(Boolean[] boolary) { if (boolary == null) { return String.Empty; } String boolliststr = String.Empty; String itemstr = String.Empty; foreach (Boolean bl in boolary) { itemstr = bl ? "1" : "0"; boolliststr = boolliststr + itemstr; } return boolliststr; } /// /// 把Boolean数组转换为数值数组 /// /// /// /// public static Boolean BooleanArrayToInt32Array(Boolean[] boolary, Int32[] intarray) { if (boolary == null || intarray == null || boolary.Length < 1 || intarray.Length < 1 || boolary.Length != intarray.Length) { return false; } for (Int32 idx = 0; idx < intarray.Length; ++idx) { intarray[idx] = boolary[idx] ? 1 : 0; } return true; } /// /// 把Boolean数组转换为数值数组 /// /// /// /// public static Int32[] BooleanArrayToInt32Array(Boolean[] boolary) { if (boolary == null || boolary.Length < 1) { return null; } Int32[] intarray = new Int32[boolary.Length]; for (Int32 idx = 0; idx < boolary.Length; ++idx) { intarray[idx] = boolary[idx] ? 1 : 0; } return intarray; } /// /// 把Boolean数组转换为数值数组 /// /// /// /// public static Boolean Int32ArrayToBooleanArray(Int32[] intarray, Boolean[] boolary) { if (boolary == null || intarray == null || boolary.Length < 1 || intarray.Length < 1 || boolary.Length != intarray.Length) { return false; } for (Int32 idx = 0; idx < intarray.Length; ++idx) { boolary[idx] = (intarray[idx] == 0) ? false : true; } return true; } /// /// 把Boolean数组转换为数值数组 /// /// /// /// public static Boolean[] Int32ArrayToBooleanArray(Int32[] intarray) { if (intarray == null || intarray.Length < 1) { return null; } Boolean[] boolary = new Boolean[intarray.Length]; for (Int32 idx = 0; idx < intarray.Length; ++idx) { boolary[idx] = (intarray[idx] == 0) ? false : true; } return boolary; } /// /// 字节转换为Int16 /// /// /// public static Int32 BytesToInt16(Byte[] bytes) { if (bytes == null || bytes.Length < 2) { return 0; } Int32 ret = bytes[0] + (bytes[1] << 8); return ret; } /// /// 字节转换为Int16 /// /// /// public static Int32 BytesToInt16(Byte[] bytes, Int32 startidx) { if (bytes == null || startidx < 0 || startidx + 2 > bytes.Length) { return 0; } Int32 ret = bytes[startidx] + (bytes[startidx + 1] << 8); return ret; } /// /// 字节转换为Int32 /// /// /// public static Int32 BytesToInt32(Byte[] bytes) { if (bytes == null || bytes.Length < 4) { return 0; } Int32 ret = bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24); return ret; } /// /// 字节转换为Int32 /// /// /// public static Int32 BytesToInt32(Byte[] bytes, Int32 startidx) { if (bytes == null || startidx < 0 || startidx + 4 > bytes.Length) { return 0; } Int32 ret = bytes[startidx] + (bytes[startidx + 1] << 8) + (bytes[startidx + 2] << 16) + (bytes[startidx + 3] << 24); return ret; } /// 将字符串转成二进制 /// /// /// public static string StringToBinary(string s) { byte[] data = Encoding.Unicode.GetBytes(s); StringBuilder result = new StringBuilder(data.Length * 8); foreach (byte b in data) { result.Append(Convert.ToString(b, 2).PadLeft(8, '0')); } return result.ToString(); } /// 将二进制转成字符串 /// /// /// public static string BinaryToString(string s) { System.Text.RegularExpressions.CaptureCollection cs = System.Text.RegularExpressions.Regex.Match(s, @"([01]{8})+").Groups[1].Captures; byte[] data = new byte[cs.Count]; for (int i = 0; i < cs.Count; i++) { data[i] = Convert.ToByte(cs[i].Value, 2); } return Encoding.Unicode.GetString(data, 0, data.Length); } /// /// <函数:Decode> /// 作用:将16进制数据编码转化为字符串,是Encode的逆过程 /// /// /// public static string Decode(string strDecode) { string sResult = ""; for (int i = 0; i < strDecode.Length / 4; i++) { sResult += (char)short.Parse(strDecode.Substring(i * 4, 4), global::System.Globalization.NumberStyles.HexNumber); } return sResult; } /// /// <函数:Encode> /// 作用:将字符串内容转化为16进制数据编码,其逆过程是Decode /// 参数说明: /// strEncode 需要转化的原始字符串 /// 转换的过程是直接把字符转换成Unicode字符,比如数字"3"-->0033,汉字"我"-->U+6211 /// 函数decode的过程是encode的逆过程. /// /// /// public static string Encode(string strEncode) { string strReturn = "";// 存储转换后的编码 foreach (short shortx in strEncode.ToCharArray()) { strReturn += shortx.ToString("X4"); } return strReturn; } 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); result += Convert.ToString(b[i], 16) + " "; } result = result.TrimEnd(); return result; } public static string HexStringToString(string hs, Encoding encode) { //以%分割字符串,并去掉空字符 //string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries); 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); } /// /// 字符串转16进制字节数组 /// /// /// public static byte[] strToToHexByte(string hexString) { //hexString = hexString.Trim(); //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; string[] chars = hexString.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 b; } /// /// 从汉字转换到16进制 /// /// /// 编码,如"utf-8","gb2312" /// 是否每字符用逗号分隔 /// 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(); } /// /// 从16进制转换成汉字 /// /// /// 编码,如"utf-8","gb2312" /// 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); } // //十进制转二进制 //Console.WriteLine("十进制166的二进制表示: "+Convert.ToString(166, 2)); // //十进制转八进制 //Console.WriteLine("十进制166的八进制表示: "+Convert.ToString(166, 8)); ////十进制转十六进制 Console.WriteLine("十进制166的十六进制表示: "+Convert.ToString(166, 16)); ////二进制转十进制 //Console.WriteLine("二进制 111101 的十进制表示: "+Convert.ToInt32("111101", 2)); // //八进制转十进制 //Console.WriteLine("八进制 44 的十进制表示: "+Convert.ToInt32("44", 8)); ////十六进制转十进制 //Console.WriteLine("十六进制 CC的十进制表示: "+Convert.ToInt32("CC", 16)); } }