代码如下
/// <summary> /// //16转2方法 /// </summary> /// <param name="hexString"></param> /// <returns></returns> static string HexString2BinString(string hexString) { try { string result = string.Empty; foreach (char c in hexString) { int v = Convert.ToInt32(c.ToString(), 16); int v2 = int.Parse(Convert.ToString(v, 2)); // 去掉格式串中的空格,即可去掉每个4位二进制数之间的空格, result += string.Format("{0:d4} ", v2); } return result; } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } /// <summary> /// 解码过程接收16进制编码转换成16进制 /// </summary> /// <param name="data"></param> public void AddData(byte[] data) { StringBuilder sb = new StringBuilder(); if (data.Length > 9) { for (int i = 0; i < 9; i++) { sb.AppendFormat("{0:x2}" + " ", data[i]); } AddContent(sb.ToString()); } else { for (int i = 0; i < data.Length; i++) { sb.AppendFormat("{0:x2}" + " ", data[i]); } AddContent(sb.ToString()); } } //使用示例代码如下 string bin = "10000111";//二进制值 string s16 = "00 5a 53 00 01 04 01 00 39";//十六进制值 Console.WriteLine("二 转 十六进制:" + string.Format("{0:x}", Convert.ToInt32(bin, 2)));//2转16 string[] strdate = s16.Split(); string sc = HexString2BinString(strdate[6]);//16转2 Console.WriteLine(sc); string jszt = sc.Replace(" ", ""); Console.WriteLine(jszt); Console.ReadKey();
标签:Console,进制,16,C#,int,互转,sb,data,string From: https://www.cnblogs.com/Kirito-Asuna-Yoyi/p/17595972.html