TCP/IP通信またはシリアル通信データ型変換

10595 ワード

        /// 
        /// string   byte[]  
        /// 
        /// 
        /// 
        public static byte[] GetBytes(string str)
        {
            byte[] bytes = new byte[str.Length * sizeof(char)];
            System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
            return bytes;
        }

        /// 
        /// byte[]     strng
        /// 
        /// 
        /// 
        public static string GetString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length / sizeof(char)];
            System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
            return new string(chars);
        }

        /// 
        ///      16     
        /// 
        /// 
        /// 
        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;
        }

        /// 
        /// byte   string
        /// 
        /// 
        /// 
        /// 
        public static string ToHexString(byte[] bytes, int len)
        {
            return ToHexString(bytes, 0, len);
        }

        public static string ToHexString(byte[] bytes, int start, int len)
        {
            string strReturn = "";
            for (int i = start; i < (start + len); i++)
            {
                byte bt = bytes[i];
                strReturn += bt.ToString("x2");
            }
            return strReturn;
        }



        /// 
        /// 16   ASCII
        /// 
        /// 
        /// 
        public static string HexToASCII(string Msg)
        {
            byte[] buff = new byte[Msg.Length / 2];
            string Message = "";
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = byte.Parse(Msg.Substring(i * 2, 2),
                   System.Globalization.NumberStyles.HexNumber);
            }

            System.Text.Encoding chs = System.Text.Encoding.ASCII;
            Message = chs.GetString(buff);
            return Message;
        }

        /// 
        ///     16      
        /// 
        /// 
        /// 
        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;
        }

        /// 
        /// 16     byte[]
        /// 
        /// 
        /// 
        public static byte[] ToByesByHex(string hexStr)
        {
            int len = hexStr.Length;

            byte[] data = new byte[len / 2];

            for (int k = 0; k < data.Length; k++)
            {
                data[k] = Convert.ToByte(hexStr.Substring(k * 2, 2), 16);
                //k = k* 2;
            }

            return data;
        }

        /// 
        ///       16  
        /// 
        /// 
        ///   , "utf-8","gb2312"
        ///           
        /// 
        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();
        }
        
        ///
        ///  16       
        /// 
        /// 
        ///   , "utf-8","gb2312"
        /// 
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("
", ""); 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); } /// /// Unicode /// /// /// public static string UnicodeToGB(string text) { System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})"); if (mc != null && mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m2 in mc) { string v = m2.Value; string word = v.Substring(2); byte[] codes = new byte[2]; int code = Convert.ToInt32(word.Substring(0, 2), 16); int code2 = Convert.ToInt32(word.Substring(2), 16); codes[0] = (byte)code2; codes[1] = (byte)code; text = text.Replace(v, Encoding.Unicode.GetString(codes)); } } else { } return text; } public static string unicodetogbx(string text) { System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(text, "\\\\u([\\w]{4})"); string a = text.Replace("\\u", ""); char[] arr = new char[mc.Count]; for (int i = 0; i < arr.Length; i++) { arr[i] = (char)Convert.ToInt32(a.Substring(i * 4, 4), 16); } string c = new string(arr); return c; } /// /// Unicode ( ) /// /// /// public static string UnicodeToCn(string text) { string cd = text; string cd2 = cd.Replace(" ", ""); cd2 = cd2.Replace("\r", ""); cd2 = cd2.Replace("
", ""); cd2 = cd2.Replace("\r
", ""); cd2 = cd2.Replace("\t", ""); if (cd2.Length % 4 != 0) { //MessageBox.Show("Unicode , ! 。"); return ""; } else { int len = cd2.Length / 2; byte[] b = new byte[len]; for (int i = 0; i < cd2.Length; i += 2) { string bi = cd2.Substring(i, 2); b[i / 2] = (byte)Convert.ToInt32(bi, 16); } string o = Encoding.Unicode.GetString(b); //textBox2.Text = o; return o; } } /// /// UniCode /// /// /// public static string StringToUnicode(string s) { char[] charbuffers = s.ToCharArray(); byte[] buffer; StringBuilder sb = new StringBuilder(); for (int i = 0; i < charbuffers.Length; i++) { buffer = System.Text.Encoding.Unicode.GetBytes(charbuffers[i].ToString()); sb.Append(String.Format("//u{0:X2}{1:X2}", buffer[1], buffer[0])); } return sb.ToString(); } /// /// Unicode /// /// /// public static string UnicodeToString(string srcText) { string dst = ""; string src = srcText; int len = srcText.Length / 6; for (int i = 0; i <= len - 1; i++) { string str = ""; str = src.Substring(0, 6).Substring(2); src = src.Substring(6); byte[] bytes = new byte[2]; bytes[1] = byte.Parse(int.Parse(str.Substring(0, 2), NumberStyles.HexNumber).ToString()); bytes[0] = byte.Parse(int.Parse(str.Substring(2, 2), NumberStyles.HexNumber).ToString()); dst += Encoding.Unicode.GetString(bytes); } return dst; }