C#字符串、字符串数组、字节、字节数组和16进制,8进制,2进制相互转换 及数字和ASCII码互转
最近做硬件物联网IOT、MQTT、TCPIP网络编程,经常被各种进制和字符串之间的转换弄的头疼,麻蛋的,索性抄袭几篇博客,合兵一处,整理如下:
不知道何时开始,很多程序员喜欢用ToLower,ToUpper去实现忽略大小写模式的字符串相等性比较,有可能这个习惯是从别的语言引进的,大胆猜测下是JS,为了不引起争论,我指的JS是技师的意思~
一:背景
1. 讲故事
在我们一个订单聚合系统中,每一笔订单都会标注来源,比如JD,Taobao,Etao,Shopex 等等一些渠道,UI上也提供高级配置输入自定义的订单来源,后来客户反馈输入xxx查询不出订单,这里就拿shopex为例,用户用小写的shopex查询,但系统中标注的是首字母大写的Shopex,所以自然无法匹配,为了解决这个问题开发小哥就统一转成大写做比对,用代码表示如下:
var orderfrom = "shopex".ToUpper();
customerIDList = MemoryOrders.Where(i =>i.OrderFrom.ToUpper()==orderFrom)
.Select(i => i.CustomerId).ToList();
改完后就是这么牛的上线了,乍一看也没啥问题,结果一查询明显感觉比之前速度慢了好几秒,干脆多点几下,好咯。。。在监控中发现CPU和memory突高突低,异常波动,这位小哥又在写bug了,查了下代码问他为什么这么写,小哥说在js中就是这么比较的~~~
2. string.Compare 改造
其实在C#中面对忽略大小写形式的比较是有专门的方法,性能高而且还不费内存,它就是 string.Compare
,所以把上面代码改成如下就可以了。
var orderfrom = "shopex";
customerIDList = MemoryOrders.Where(string.Compare(i.TradeFrom, tradefrom,
StringComparison.OrdinalIgnoreCase) == 0)
.Select(i => i.CustomerId).ToList();
这其中的 StringComparison.OrdinalIgnoreCase
枚举就是用来忽略大小写的,上线之后除了CPU还是有点波动,其他都没有问题了。
1.请问c#中如何将十进制数的字符串转化成十六进制数的字符串
//十进制转二进制
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));
2.在串口通讯过程中,经常要用到 16进制与字符串、字节数组之间的转换
private 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; } private 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); } /// <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进制字符串 /// </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> /// 从汉字转换到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); }
1.字符串=>比特数组
(1)byte[] bt=System.Text.Encoding.Default.GetBytes("字符串"); (2)byte[] bt=Convert.FromBase64String("字符串");
补充:
System.Text.Encoding.Unicode.GetBytes(str); System.Text.Encoding.UTF8.GetBytes(str); System.Text.Encoding.GetEncoding("gb2312").GetBytes(str); //指定编码方式
string str = "中国?ss123?"; byte[] bytes = System.Text.Encoding.Default.GetBytes(str); //gb2312编码 汉字占2个字节、英文字母占1个字节 bytes长度为12 string s = System.Text.Encoding.Default.GetString(new byte[] { bytes[0],bytes[1] });//解码后为“中”
byte[] bytes = {97, 98, 99, 100, 101, 102}; string str = System.Text.Encoding.ASCII.GetString(bytes); //结果为:abcdef ASCII码表
常用方法:
GetString 已重载。 在派生类中重写时,将一个字节序列解码为一个字符串。 GetChars 已重载。 在派生类中重写时,将一个字节序列解码为一组字符。 GetBytes 已重载。 在派生类中重写时,将一组字符编码为一个字节序列。 GetByteCount 已重载。 在派生类中重写时,计算对一组字符进行编码所产生的字节数。 GetCharCount 已重载。 在派生类中被重写时,计算对字节序列进行解码所产生的字符数。 GetDecoder 在派生类中重写时,获取一个解码器,该解码器将已编码的字节序列转换为字符序列。 GetEncoder 在派生类中重写时,获取一个解码器,该解码器将Unicode字符序列转换为已编码的字节序列
2.比特数组=>字符串
(1)string str=System.Text.Encoding.Default.GetString(bt); (2)string str=Convert.ToBase64String(bt);
3.字符串=>流
(1)MemoryStream ms=new MemoryStream(System.Text.Encoding.Default.GetBytes("字符串")); (2)MemoryStream ms=new MemoryStream(Convert.FromBase64String("字符串"));
4.流=>字符串
(1)string str=Convert.ToBase64String(ms.ToArray()); (2)string str=System.Text.Encoding.Default.GetString(ms.ToArray());
5.比特数组=>流
(1)MemoryStream ms=new MemoryStream(bt); (2)MemoryStream ms=new MemoryStream();ms.Read(bt,0,bt.Lenght);
6.流=>比特数组
(1)byte[] bt=ms.ToArray(); (2)MemoryStream ms=new MemoryStream();ms.Write(bt,0,ms.Length);
7、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."); } }
实战,解析如下字符串:
0x78,0x32,0x61,0x61,0x30,0x32,0x30,0x30,0x39,0x30,0x37,0x30,0x30,0x30,0x30,0x31,0x02,0x58,0x00,0xC8,0x02,0x74,0x00,0x00,0x4E,0x39,0x00,0x00,0x00,0x01,0x1D,0x00,0x02,0x00,0x61,0x0C,0xF0,0x0C,0xEC,0x44,0x44,0x13,0x0C,0xEC,0x0C,0xED,0x0C,0xED,0x0C,0xED,0x0C,0xEC,0x0C,0xEC,0x0C,0xF0,0x0C,0xEF,0x0C,0xEC,0x0C,0xEF,0x0C,0xEF,0x0C,0xEF,0x0C,0xEE,0x0C,0xEE,0x0C,0xEE,0x0C,0xEF,0x0C,0xEE,0x0C,0xEE,0x0C,0xED,0x02,0x44,0x44,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class btinfoModel { public Dictionary<string, int> Dic = new Dictionary<string, int>(); public btinfoModel() { } public btinfoModel(string btinfo) { if (string.IsNullOrEmpty(btinfo)) { return; } var By48 = btinfo.Replace("0x", ""); var ByAry = By48.Split(',').ToList(); List<int> lst = new List<int>(); foreach (var item in ByAry) { var No = Convert.ToInt32(item, 16); lst.Add(No); //Console.WriteLine("数值为:" + No); } Dictionary<string, int> Dic = new Dictionary<string, int>(); Dic.Add("BettaryNum", 16);//电池编号 Dic.Add("Voltage", 2);//电池电压 Dic.Add("Caption", 2);//电池容量 Dic.Add("TotalVoltage", 2);//总电压 Dic.Add("Electric", 2);//电流 Dic.Add("BettaryStatus", 1);//电池状态 Dic.Add("SOC", 1);//soc 电量 Dic.Add("MOS", 1);//MOS状态 Dic.Add("ljfdrl", 2);//累计放电容量 Dic.Add("ljcdrl", 2);//累计充电容量 Dic.Add("softVersion", 2);//软件版本号 Dic.Add("heardWareVersion", 2);//硬件版本号 Dic.Add("MaxSigVoltage", 2);//最大单体电压 Dic.Add("MinSigVoltage", 2);//最小单体电压 Dic.Add("MaxTemperature", 1);//最大温度 Dic.Add("MinTemperature", 1);//最小温度 var SkipVoltageNum = 0; foreach (var item in Dic) { SkipVoltageNum += item.Value; } Dic.Add("VoltageNum", 1);//电压个数 var VoltageNum = lst.Skip(SkipVoltageNum).Take(1).ToList()[0]; Dic.Add("SigVoltage", VoltageNum * 2);//单体电压 var SkipTemperature = 0; foreach (var item in Dic) { SkipTemperature += item.Value; } Dic.Add("TemperatureNum", 1);//温度个数 var TemperatureNum = lst.Skip(SkipTemperature).Take(1).ToList()[0]; Dic.Add("SigTemperature", TemperatureNum * 1);//单体温度 Dic.Add("Mos_1", 1);//Mos_1 Dic.Add("Mos_2", 1);//Mos_2 Dic.Add("Police", 2);//报警 Dic.Add("ljqcbcs", 2);//连接器插拔次数 Dic.Add("ljcdcs", 2);//累计充电次数 Dic.Add("cdqcdcs", 2);//充电器充电次数 Dic.Add("dgcdcs", 2);//电柜充电次数 Dic.Add("ggStatus", 1);//观感状态 //var TotalLength = 0; //foreach (var item in Dic) //{ // TotalLength += item.Value; //} int TotalNum = 0; foreach (var item in Dic) { var result = lst.Skip(TotalNum).Take(item.Value).ToList(); TotalNum += item.Value; switch (item.Key) { case "BettaryNum": this.BettaryNum = GetAsciiByIntAry(result); break; case "Voltage": this.Voltage = GetValue(result); break; case "Caption": this.Caption = GetValue(result); break; case "TotalVoltage": this.TotalVoltage = GetValue(result); break; case "Electric": this.Electric = GetValue(result); break; case "BettaryStatus": this.BettaryStatus = GetValue(result); break; case "SOC": this.SOC = GetValue(result); break; case "MOS": this.MOS = GetValue(result); break; case "ljfdrl": this.ljfdrl = GetValue(result); break; case "ljcdrl": this.ljcdrl = GetValue(result); break; case "softVersion": this.softVersion = GetValue(result); break; case "heardWareVersion": this.heardWareVersion = GetValue(result); break; case "MaxSigVoltage": this.MaxSigVoltage = GetValue(result); break; case "MinSigVoltage": this.MinSigVoltage = GetValue(result); break; case "MaxTemperature": this.MaxTemperature = GetValue(result)-40; break; case "MinTemperature": this.MinTemperature = GetValue(result)-40; break; case "VoltageNum": this.VoltageNum = GetValue(result); break; case "SigVoltage": this.SigVoltage = string.Join(",", GetSigVoltageValue(result)); break; case "TemperatureNum": this.TemperatureNum = GetValue(result); break; case "SigTemperature": this.SigTemperature = GetSigTemperature(result); break; case "Mos_1": this.Mos_1 = GetValue(result)-40; break; case "Mos_2": this.Mos_2 = GetValue(result)-40; break; case "Police": this.Police = GetValue(result); break; case "ljqcbcs": this.ljqcbcs = GetValue(result); break; case "ljcdcs": this.ljcdcs = GetValue(result); break; case "cdqcdcs": this.cdqcdcs = GetValue(result); break; case "dgcdcs": this.dgcdcs = GetValue(result); break; case "ggStatus": this.ggStatus = GetValue(result); break; } } } public string BettaryNum { get; set; } //电池串号 16位 public int Voltage { get; set; } //电池电压 public int Caption { get; set; } //电池容量 public int TotalVoltage { get; set; } //总电压 public int Electric { get; set; } //电流 public int BettaryStatus { get; set; } //电池状态 public string BettaryStatusString { get { return GetBattaryStatus(BettaryStatus); } } //电池状态 public int SOC { get; set; } //soc 电量 public int MOS { get; set; } //MOS状态 public string MOSEjz { get { return GetEjzByInt(MOS, 8); } } //MOS状态 二进制 public string MOSEjzString { get { return GetMosEjzString(MOSEjz); } } //MOS状态 中文 public int ljfdrl { get; set; } //累计放电容量 public int ljcdrl { get; set; } //累计充电容量 public int softVersion { get; set; } //软件版本号 public int heardWareVersion { get; set; } //硬件版本号 public int MaxSigVoltage { get; set; } //最大单体电压 public int MinSigVoltage { get; set; } //最小单体电压 public int MaxTemperature { get; set; } //最大温度 public int MinTemperature { get; set; } //最小温度 public int VoltageNum { get; set; } //电压个数 public string SigVoltage { get; set; } //单体电压 = 电压个数*2 public int TemperatureNum { get; set; } //温度个数 public string SigTemperature { get; set; } //单体温度 =温度个数*1 public int Mos_1 { get; set; } //Mos_1 public int Mos_2 { get; set; } //Mos_2 public int Police { get; set; } //报警 public string PoliceEjz { get { return GetEjzByInt(Police); } }//報警二進制 public string PoliceEjzString { get { return GetEjzString(PoliceEjz); } }//報警二進制对应的报警值 中文 public int ljqcbcs { get; set; } //连接器插拔次数 public int ljcdcs { get; set; } //累计充电次数 public int cdqcdcs { get; set; } //充电器充电次数 public int dgcdcs { get; set; } //电柜充电次数 public int ggStatus { get; set; } //观感状态 #region 方法集 /// <summary> /// 获取电池状态 /// </summary> /// <param name="sb"></param> /// <returns></returns> private string GetBattaryStatus(int sb) { var result = GetAsciiByInt(sb); if (result == "C") { return "充电"; } else if (result == "D") { return "放电"; } else if (result == "N") { return "静止"; } return "暂无电池状态"; } /// <summary> /// 获取电池串号 /// </summary> /// <param name="Ary"></param> /// <returns></returns> private string GetAsciiByIntAry(List<int> Ary) { string result = string.Empty; foreach (var item in Ary) { result += GetAsciiByInt(item); } return result; } /// <summary> /// 根据数字获取ASCII码 /// </summary> /// <param name="num"></param> /// <returns></returns> private string GetAsciiByInt(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."); } } /// <summary> /// 16进制转十进制 具体参考十六进制的数值 /// </summary> /// <param name="Ary"></param> /// <returns></returns> private int GetValue(List<int> Ary) { double result = 0; var cm = 0; cm = Ary.Count; foreach (var item in Ary) { if (cm - 1 == 0) { result += item; } else { result += item * Math.Pow(16, (cm * 2 - 2)); cm--; } } return Convert.ToInt32(result); } /// <summary> /// 计算单体电压 单体电压占2字节,因此需要两字节合兵一起计算 /// </summary> /// <param name="Ary"></param> /// <returns></returns> private List<int> GetSigVoltageValue(List<int> SigVoltage) { List<int> AeryList = new List<int>(); var cc = SigVoltage.Count; for(int i = 0; i < cc / 2; i++) { var Aery = SigVoltage.Skip(i * 2).Take(2).ToList(); var result = GetValue(Aery); AeryList.Add(result); } return AeryList; } private string GetSigTemperature(List<int> Ary) { List<int> result = new List<int>(); foreach (var item in Ary) { var citem = item - 40; result.Add(citem); } return string.Join(",", result.ToArray()); } /// <summary> /// /// </summary> /// <param name="Number">数字</param> /// <param name="bitNum">位数 16位沾二字节 8位占一字节</param> /// <returns></returns> private string GetEjzByInt(int Number,int bitNum=16) { var result = Convert.ToString((ushort)Number, 2); var len = result.Length; if (len < 16) { for (int i = 0; i < bitNum - len; i++) { result = "0" + result; } } return result; } /// <summary> /// 根据二进制 获取报警值 /// 0000000000000011 數字3 從右至左移位 非别为0到15位 /// </summary> /// <param name="ejz"></param> /// <returns></returns> private string GetEjzString(string ejz) { string result = string.Empty; var charAry = ejz.ToCharArray(); foreach (var item in charAry) { if (item.ToString() == "1") { switch (charAry.ToList().IndexOf(item)) { case 0: result+="MOS温度高_"; break; case 1: result+= "短路_"; break; case 2: result+= "放电低温_"; break; case 3: result+= "放电高温_"; break; case 4: result+= "充电低温_"; break; case 5: result+= "充电高温_"; break; case 6: result+=""; break; case 7: result+=""; break; case 8: result+= "SOC低_"; break; case 9: result+= "充电过流_"; break; case 10: result+= "放电过流_"; break; case 11: result+=""; break; case 12: result+=""; break; case 13: result+= "单体欠压_"; break; case 14: result+= "单体过压_"; break; case 15: result+= "盲充过流_"; break; } } } return result; } private string GetMosEjzString(string ejz) { string result = string.Empty; var charAry = ejz.ToCharArray(); foreach (var item in charAry) { if (item.ToString() == "1") { switch (charAry.ToList().IndexOf(item)) { case 0: result += ""; break; case 1: result += ""; break; case 2: result += ""; break; case 3: result += ""; break; case 4: result += ""; break; case 5: result += ""; break; case 6: result += "放电"; break; case 7: result += "充电"; break; } } } return result; } #endregion }
结果:
@天才卧龙的博客