本文共 1621 字,大约阅读时间需要 5 分钟。
byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);
string str = System.Text.Encoding.Default.GetString(byteArray);
输入字符串"0011AACCBB" 输出 字节数组0x00,0x11,0xAA,0xCC,0xBB
//参数:"0011AACCBB" return 字节数组0x00,0x11,0xAA,0xCC,0xBBpublic 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;}
输入字符串"00 11 AA CC BB" 输出字节数组0x00,0x11,0xAA,0xCC,0xBB
//参数:"00 11 AA CC BB" return 字节数组0x00,0x11,0xAA,0xCC,0xBBpublic static byte[] strToHexByteSplit(string hexString){ return hexString.Split(' ').Select(temp => "0x" + temp).Select(temp => (byte)Convert.ToInt32(temp, 16)).ToArray();}
输入字节数组0x00,0x11,0xAA,0xCC,0xBB 输出字符串0011AACCBB也可带分隔符
//参数:字节数组0x00,0x11,0xAA,0xCC,0xBB return 0011AACCBB也可带分隔符public static string HexToStr(byte[] hexbyte){ return BitConverter.ToString(hexbyte).Replace("-","");}
public static string HexToStr(string mHex){ mHex = mHex.Replace(" ", ""); if (mHex.Length <= 0) return ""; byte[] vBytes = new byte[mHex.Length / 2]; for (int i = 0; i < mHex.Length; i += 2) if (!byte.TryParse(mHex.Substring(i, 2), NumberStyles.HexNumber, null, out vBytes[i / 2])) vBytes[i / 2] = 0; return ASCIIEncoding.Default.GetString(vBytes);}
转载地址:http://zyulf.baihongyu.com/