进制转换的基础知识这里不多做解释,不清楚的翻一翻数学课本。在工业控制中,经常用到各种进制转换,单片机的二进制控制引脚高低电平,PLC的16进制串口数据传输等等,所以我们有必要弄清楚各种进制转换,下面C#方法搜集自网络。
注意:在转换时一定要区分字符与数字,特别是中文,不同编码方式占用的字节数量不一样,导致转换16进制位数不同!
数字转换
Convert类中定义了相关转换方法
//// 摘要:// 将 32 位带符号整数的值转换为其指定基的等效字符串表示形式。//// 参数:// value:// 要转换的 32 位带符号整数。//// toBase:// 返回值的基数,必须是 2、8、10 或 16。//// 返回结果:// 以 toBase 为基数的 value 的字符串表示形式。//// 异常:// T:System.ArgumentException:// toBase 不是 2、8、10 或 16。[SecuritySafeCritical]public static string ToString(int value, int toBase);
实例
//十进制转二进制字符串 Console.WriteLine(Convert.ToString(0, 2)); Console.WriteLine(Convert.ToString(3, 2));
// // 摘要: // 将指定基数的数字的字符串表示形式转换为等效的 32 位有符号整数。 // // 参数: // value: // 包含要转换的数字的字符串。 // // fromBase: // value 中数字的基数,它必须是 2、8、10 或 16。 // // 返回结果: // 与 value 中数字等效的 32 位带符号整数,如果 value 为 null,则为 0(零)。 // // 异常:省略 public static int ToInt32(string value, int fromBase);
实例
//二进制转十进制 Console.WriteLine(Convert.ToInt32("00", 2)); Console.WriteLine(Convert.ToInt32("01", 2)); Console.WriteLine(Convert.ToInt32("11", 2));
字符串转换
/// <summary> /// 将指定进制的字符串,转换成十进制 /// </summary> /// <param name="source">字符串</param> /// <param name="number">进制数</param> /// <returns></returns> public static int ConvertFromN(string source, int fromBase) { char[] list = source.ToCharArray(); var r = 0; for (int i = list.Length - 1; i >= 0; i--) { int value = Convert.ToInt32(list[i].ToString()); r += (int)Math.Pow(fromBase, list.Length - i - 1) * value; } return r; }
实例
//二进制 Console.WriteLine(ConvertFromN("00", 2));//0 Console.WriteLine(ConvertFromN("11", 2));//3 //三进制 Console.WriteLine(ConvertFromN("010", 3));//3 Console.WriteLine(ConvertFromN("110", 3));//12
下面是网友们自己手写的算法
/// <summary> /// 十进制转换为二进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string DecToBin(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X%2; X = X/2; b = b + a*Pow(10, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 16进制转ASCII码 /// </summary> /// <param name="hexString"></param> /// <returns></returns> public static string HexToAscii(string hexString) { StringBuilder sb = new StringBuilder(); for (int i = 0; i <= hexString.Length - 2; i += 2) { sb.Append( Convert.ToString( Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber)))); } return sb.ToString(); } /// <summary> /// 十进制转换为八进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string DecToOtc(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X%8; X = X/8; b = b + a*Pow(10, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 十进制转换为十六进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string DecToHex(string x) { if (string.IsNullOrEmpty(x)) { return "0"; } string z = null; int X = Convert.ToInt32(x); Stack a = new Stack(); int i = 0; while (X > 0) { a.Push(Convert.ToString(X%16)); X = X/16; i++; } while (a.Count != 0) z += ToHex(Convert.ToString(a.Pop())); if (string.IsNullOrEmpty(z)) { z = "0"; } return z; } /// <summary> /// 二进制转换为十进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string BinToDec(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X%10; X = X/10; b = b + a*Pow(2, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 二进制转换为十进制,定长转换 /// </summary> /// <param name="x"></param> /// <param name="iLength"></param> /// <returns></returns> public static string BinToDec(string x, short iLength) { StringBuilder sb = new StringBuilder(); int iCount = 0; iCount = x.Length/iLength; if (x.Length%iLength > 0) { iCount += 1; } int X = 0; for (int i = 0; i < iCount; i++) { if ((i + 1)*iLength > x.Length) { X = Convert.ToInt32(x.Substring(i*iLength, (x.Length - iLength))); } else { X = Convert.ToInt32(x.Substring(i*iLength, iLength)); } int j = 0; long a, b = 0; while (X > 0) { a = X%10; X = X/10; b = b + a*Pow(2, j); j++; } sb.AppendFormat("{0:D2}", b); } return sb.ToString(); } /// <summary> /// 二进制转换为十六进制,定长转换 /// </summary> /// <param name="x"></param> /// <param name="iLength"></param> /// <returns></returns> public static string BinToHex(string x, short iLength) { StringBuilder sb = new StringBuilder(); int iCount = 0; iCount = x.Length/iLength; if (x.Length%iLength > 0) { iCount += 1; } int X = 0; for (int i = 0; i < iCount; i++) { if ((i + 1)*iLength > x.Length) { X = Convert.ToInt32(x.Substring(i*iLength, (x.Length - iLength))); } else { X = Convert.ToInt32(x.Substring(i*iLength, iLength)); } int j = 0; long a, b = 0; while (X > 0) { a = X%10; X = X/10; b = b + a*Pow(2, j); j++; } //前补0 sb.Append(DecToHex(b.ToString())); } return sb.ToString(); } /// <summary> /// 八进制转换为十进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string OctToDec(string x) { string z = null; int X = Convert.ToInt32(x); int i = 0; long a, b = 0; while (X > 0) { a = X%10; X = X/10; b = b + a*Pow(8, i); i++; } z = Convert.ToString(b); return z; } /// <summary> /// 十六进制转换为十进制 /// </summary> /// <param name="x"></param> /// <returns></returns> public static string HexToDec(string x) { if (string.IsNullOrEmpty(x)) { return "0"; } string z = null; Stack a = new Stack(); int i = 0, j = 0, l = x.Length; long Tong = 0; while (i < l) { a.Push(ToDec(Convert.ToString(x[i]))); i++; } while (a.Count != 0) { Tong = Tong + Convert.ToInt64(a.Pop())*Pow(16, j); j++; } z = Convert.ToString(Tong); return z; } #endregion //Helperfunctions /// <summary> /// /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> private static long Pow(long x, long y) { int i = 1; long X = x; if (y == 0) return 1; while (i < y) { x = x*X; i++; } return x; } /// <summary> /// /// </summary> /// <param name="x"></param> /// <returns></returns> private static string ToDec(string x) { switch (x) { case "A": return "10"; case "B": return "11"; case "C": return "12"; case "D": return "13"; case "E": return "14"; case "F": return "15"; default: return x; } } /// <summary> /// /// </summary> /// <param name="x"></param> /// <returns></returns> private static string ToHex(string x) { switch (x) { case "10": return "A"; case "11": return "B"; case "12": return "C"; case "13": return "D"; case "14": return "E"; case "15": return "F"; default: return x; } } /// <summary> /// 将16进制BYTE数组转换成16进制字符串 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF " { string hexString = string.Empty; if (bytes != null) { StringBuilder strB = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return hexString; } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <param name="iLength"></param> /// <returns></returns> public static string ToHexString(byte[] bytes, int iLength) // 0xae00cf => "AE00CF " { string hexString = string.Empty; if (bytes != null) { StringBuilder strB = new StringBuilder(); if (bytes.Length < iLength) { iLength = bytes.Length; } for (int i = 0; i < iLength; i++) { strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return hexString; } /// <summary> /// 将byte数组转换为16进制字符串 /// </summary> /// <param name="bytes">要转换的数组</param> /// <param name="iStart">数组下标</param> /// <param name="iLength">长度</param> /// <returns></returns> public static string ToHexString(byte[] bytes, int iStart, int iLength) // 0xae00cf => "AE00CF " { string hexString = string.Empty; if (bytes != null) { StringBuilder strB = new StringBuilder(); //缓冲区长度问题,需清空缓冲区 if (bytes.Length < (iLength + iStart)) { iLength = bytes.Length; } for (int i = iStart; i < iLength + iStart; i++) { strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return hexString; } /// <summary> /// /// </summary> /// <param name="hexString"></param> /// <param name="discarded"></param> /// <returns></returns> public static byte[] GetBytes(string hexString, out int discarded) { discarded = 0; string newString = ""; char c; // remove all none A-F, 0-9, characters for (int i = 0; i < hexString.Length; i++) { c = hexString[i]; if (Uri.IsHexDigit(c)) newString += c; else discarded++; } // if odd number of characters, discard last character if (newString.Length%2 != 0) { discarded++; newString = newString.Substring(0, newString.Length - 1); } return HexToByte(newString); } /// <summary> /// Converts from binary coded decimal to integer /// </summary> /// <param name="num"></param> /// <returns></returns> public static uint BcdToDec(uint num) { return HornerScheme(num, 0x10, 10); } /// <summary> /// Converts from integer to binary coded decimal /// </summary> /// <param name="num"></param> /// <returns></returns> public static uint DecToBcd(uint num) { return HornerScheme(num, 10, 0x10); } private static uint HornerScheme(uint num, uint divider, uint factor) { uint remainder = 0, quotient = 0, result = 0; remainder = num%divider; quotient = num/divider; if (!(quotient == 0 && remainder == 0)) result += HornerScheme(quotient, divider, factor)*factor + remainder; return result; } /// <summary> /// byte数组尾部0截取函数 /// </summary> /// <param name="buf">原始byte数组</param> /// <param name="iLength">要截取的长度</param> /// <returns>截取后的数组</returns> public static byte[] InterceptByte(byte[] buf, int iLength) { StringBuilder sb = new StringBuilder(iLength*2); sb = sb.Append(ToHexString(buf, (short) iLength)); int discarded = 0; byte[] bReturn = GetBytes(sb.ToString(), out discarded); if (discarded > 0) { throw new Exception("byte数组截取有数据丢失!"); } return bReturn; } /// <summary> /// /// </summary> /// <param name="hexString"></param> /// <returns></returns> public static byte[] HexToByte(string hexString) { if (string.IsNullOrEmpty(hexString)) { hexString = "00"; } 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> /// 日期转BCD数组 /// </summary> /// <param name="dateTime"></param> /// <param name="type">4 6 7</param> /// <returns></returns> public static byte[] DateTimeToBCD(DateTime dateTime, ushort type) { string strServerTime = string.Format("{0:yyyyMMddHHmmss}", dateTime); byte[] bcd = new byte[type]; if (type == 4) { bcd[0] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(0, 2))).ToString("D2")); bcd[1] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(2, 2))).ToString("D2")); bcd[2] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(4, 2))).ToString("D2")); bcd[3] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(6, 2))).ToString("D2")); } if (type == 6) { bcd[0] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(2, 2))).ToString("D2")); bcd[1] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(4, 2))).ToString("D2")); bcd[2] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(6, 2))).ToString("D2")); bcd[3] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(8, 2))).ToString("D2")); bcd[4] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(10, 2))).ToString("D2")); bcd[5] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(12, 2))).ToString("D2")); } if (type == 7) { bcd[0] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(0, 2))).ToString("D2")); bcd[1] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(2, 2))).ToString("D2")); bcd[2] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(4, 2))).ToString("D2")); bcd[3] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(6, 2))).ToString("D2")); bcd[4] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(8, 2))).ToString("D2")); bcd[5] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(10, 2))).ToString("D2")); bcd[5] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(12, 2))).ToString("D2")); } return bcd; } /// <summary> /// BCD时间转日期时间 /// </summary> /// <param name="bcdTime"></param> /// <param name="type"></param> /// <returns></returns> public static DateTime BCDToDateTime(byte[] bcdTime, ushort type) { StringBuilder sb = new StringBuilder(); if (type == 4) //4位BCD码的日期 { sb.Append(BcdToDec(bcdTime[0]).ToString("D2")); sb.Append(BcdToDec(bcdTime[1]).ToString("D2")); sb.Append('-' + BcdToDec(bcdTime[2]).ToString("D2")); sb.Append('-' + BcdToDec(bcdTime[3]).ToString("D2") + " "); } if (type == 6) //6位BCD码的时间 { sb.Append(DateTime.Now.ToString("yyyy").Substring(0, 2)); sb.Append(BcdToDec(bcdTime[0]).ToString("D2")); sb.Append('-' + BcdToDec(bcdTime[1]).ToString("D2")); sb.Append('-' + BcdToDec(bcdTime[2]).ToString("D2") + " "); sb.Append(BcdToDec(bcdTime[3]).ToString("D2") + ":"); sb.Append(BcdToDec(bcdTime[4]).ToString("D2") + ":"); sb.Append(BcdToDec(bcdTime[5])); } if (type == 7) //7位BCD码的日期 { sb.Append(BcdToDec(bcdTime[0]).ToString("D2")); sb.Append(BcdToDec(bcdTime[1]).ToString("D2")); sb.Append('-' + BcdToDec(bcdTime[2]).ToString("D2")); sb.Append('-' + BcdToDec(bcdTime[3]).ToString("D2") + " "); sb.Append(BcdToDec(bcdTime[4]).ToString("D2") + ":"); sb.Append(BcdToDec(bcdTime[5]).ToString("D2") + ":"); sb.Append(BcdToDec(bcdTime[6])); } DateTime dt; //2011-3-26 当日期出错时的处理 DateTime.TryParse(sb.ToString(), out dt); return dt; } } }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/241252.html