最近做有关读卡器的程序开发,进行串口通信时,需要使用16进制的数据,而在c#中我们常常使用10进制的数据,这就涉及到10--16进制之间数据转换的问题。网络上现有的代码要么不好用,要么有错误,这里写了一个帮助类,分享出来,需要的兄弟们可以放心使用。 Title using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Globalization;namespace Rare.Card.Libary.Helper{ /// <summary> /// 进制转换的帮助类 /// </summary> public class ConvertHelper { private static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; /// <summary> /// 字节数组转16进制字符串 /// </summary> /// <param name="bytes">字节数组</param> /// <returns>16进制字符串</returns> public static string byteToHexString(byte[] bytes) { string strResult = string.Empty; foreach (byte byt in bytes) { strResult += string.Format("0x{0}", byt.ToString("x2")) + ","; } if (strResult.Length > 1) { strResult = strResult.Substring(0, strResult.Length - 1); } return strResult; } /// <summary> /// 字符串逐字符转16进制字节数组 /// </summary> /// <param name="str">字符串</param> /// <returns>16进制数组</returns> public static byte[] StringToHexByte(string str) { char[] values = str.ToCharArray(); string hexString = string.Empty; foreach (char letter in values) { // Get the integral value of the character. int value = Convert.ToInt32(letter); // Convert the decimal value to a hexadecimal value in string form. hexString += String.Format("{0:X}", value); } byte[] hexOut = HexStringToHexByte(hexString); return hexOut; } /// <summary> /// 字符串转化成每个字符所代表的整形的数组 /// </summary> /// <param name="str">字符串</param> /// <returns>整形数组</returns> public static int[] StringToIntArray(string str) { char[] values = str.ToCharArray(); int[] intarry = new int[values.Length]; for (int i = 0; i < values.Length; i++) { intarry[i] = Convert.ToInt32(values[i]); } return intarry; } /// <summary> /// 16进制字符串转字节数组 /// </summary> /// <param name="str">16进制字符串</param> /// <returns>字节数组</returns> public static byte[] HexStringToHexByte(string str) { str = str.Replace(" ", ""); if ((str.Length % 2) != 0) str += " "; byte[] returnBytes = new byte[str.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) { //returnBytes[i] = Convert.ToByte(str.Substring(i * 2, 2), NumberStyles.HexNumber); returnBytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16); } return returnBytes; } /// <summary> /// 字节数组转16进制字符串数组 /// </summary> /// <param name="temp">字节数组</param> /// <param name="len">需要转换的长度,默认为字节数组的长度</param> /// <returns>字符串数组</returns> public static string[] ByteArrayToHexStringArray(byte[] temp,int len) { if (len == 0) len = temp.Length; string[] hexArray = new string[len]; for (int u = 0; u < len; u++) { hexArray[u] = string.Format("0x{0:x2}", temp[u]); } return hexArray; } }} 代码在vs2010下使用没有问题。 相关文章: 2021-12-01 2021-12-10 2021-08-25 2021-11-26 2021-11-03 2022-12-23 2021-12-04